Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript regular expression - string to RegEx object

Tags:

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.

like image 405
shake Avatar asked Jan 04 '11 00:01

shake


People also ask

How do you pass a string in regex?

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() .

Is regex an object in JavaScript?

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 .

What is difference [] and () in regex?

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.

What does '$' mean in regex?

$ means "Match the end of the string" (the position after the last character in the string).


1 Answers

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); 
like image 59
RoToRa Avatar answered Oct 03 '22 23:10

RoToRa