26

I am sure its something pretty small that I am missing but I haven't been able to figure it out.

I have a JavaScript variable with the regex pattern in it but I cant seem to be able to make it work with the RegEx class

the following always evaluates to false:

var value = "[email protected]";
var pattern = "^\w+@[a-zA-Z_]+?\.[a-zA-Z]{2,3}$"
var re = new RegExp(pattern);
re.test(value);

but if I change it into a proper regex expression (by removing the quotes and adding the / at the start and end of the pattern), it starts working:

var value = "[email protected]";
var pattern = /^\w+@[a-zA-Z_]+?\.[a-zA-Z]{2,3}$/
var re = new RegExp(pattern);
re.test(value);

since I always get the pattern as a string in a variable, I haven't been able to figure out what I am missing here.

1 Answer 1

32

Backslashes are special characters in strings that need to be escaped with another backslash:

var value = "[email protected]";
var pattern = "^\\w+@[a-zA-Z_]+?\\.[a-zA-Z]{2,3}$"
var re = new RegExp(pattern);
re.test(value);
Sign up to request clarification or add additional context in comments.

2 Comments

omg I knew it was something pretty simple that i was missing. Thanks!!
It isn't pretty simple if you change the example.

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.