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.
Note: Regex can be created in two ways first one is regex literal and the second one is regex constructor method ( new RegExp() ). If we try to pass a variable to the regex literal pattern it won't work. The right way of doing it is by using a regular expression constructor new RegExp() .
In JavaScript, regular expressions are also objects. These patterns are used with the exec() and test() methods of RegExp , and with the match() , matchAll() , replace() , replaceAll() , search() , and split() methods of String .
In other words, square brackets match exactly one character. (a-z0-9) will match two characters, the first is one of abcdefghijklmnopqrstuvwxyz , the second is one of 0123456789 , just as if the parenthesis weren't there. The () will allow you to read exactly which characters were matched.
$ means "Match the end of the string" (the position after the last character in the string).
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With