0

How to declare associative array of regex? This is not working

var Validators = {

    url : /^http(s?)://((\w+\.)?\w+\.\w+|((2[0-5]{2}|1[0-9]{2}|[0-9]{1,2})\.){3}(2[0-5]{2}|1[0-9]{2}|[0-9]{1,2}))(/)?$/gm   

};

EDITED: Now working!

This will be valid in JS (like @ operator in C#)

url : `/^http(s?)://((\w+\.)?\w+\.\w+|((2[0-5]{2}|1[0-9]{2}|[0-9]{1,2})\.){3}(2[0-5]{2}|1[0-9]{2}|[0-9]{1,2}))(/)?$/gm`

However, will still not work due to double escape, one in JS and other in Regex. If expression is small, perhaps naked eye can manually escape for both JS and Regex. My brain just can't :)

In order to use strings as tested on regex101.com for example, all required strings should be declared as 'row' like this:

var exp = String.raw`^(http(s?):\/\/)?(((www\.)?[a-zA-Z0-9\.\-\_]+(\.[a-zA-Z]{2,3})+)|(\b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b))(\/[a-zA-Z0-9\_\-\s\.\/\?\%\#\&\=]*)?$`;



var strings = [
    String.raw`http://www.goo gle.com`,
    String.raw`http://www.google.com`,
    ];
4
  • don't use g. that makes them sticky. Commented Jun 25, 2017 at 18:36
  • 1
    Well your code is throwing a syntax error, fix your regex so it doesn't have a syntax error and try again Commented Jun 25, 2017 at 18:49
  • 1
    To help you troubleshoot that syntax error, paste your regular expression (only the part between the / /, not including the slashes) into regex101.com and then take note of the error messages and the red highlights. They will show you exactly what to fix. Commented Jun 25, 2017 at 18:59
  • "This is not working" is not a useful problem description. We don't know how you expect it to "work". Commented Jun 25, 2017 at 19:14

2 Answers 2

1

Wrap it with new RegExp() and escape slashes

var Validators = {

    url : new RegExp( /^http(s?):\/\/((\w+\.)?\w+\.\w+|((2[0-5]{2}|1[0-9]{2}|[0-9]{1,2})\.){3}(2[0-5]{2}|1[0-9]{2}|[0-9]{1,2}))(\/)?$/gm ) 

};
Sign up to request clarification or add additional context in comments.

1 Comment

I accepted your answer and vote because you gave me the clue :) can be escaped with `` in JS. Thanks!
1

Your regex has forward slashes in it. This symbol needs to be escaped because it is supposed to indicate the start and end of the expression. Try \/.

1 Comment

Thanks. I tested and indeed, regex is broken. I just took from another StackOverflow.. hmm... this means that some people should test their code before post as valid answers.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.