Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to put variable in regular expression match?

I have the following snippet. I want to find the appearance of a, but it does not work. How can I put the variable right?

var string1 = 'asdgghjajakhakhdsadsafdgawerwweadf'; var string2 = 'a'; string1.match('/' + string2 + '/g').length; 
like image 890
somebodyelse Avatar asked Aug 13 '11 21:08

somebodyelse


People also ask

Can I put a variable in regex?

It's not reeeeeally a thing. There is the regex constructor which takes a string, so you can build your regex string which includes variables and then pass it to the Regex cosntructor.

How do you match a regular expression?

To match a character having special meaning in regex, you need to use a escape sequence prefix with a backslash ( \ ). E.g., \. matches "." ; regex \+ matches "+" ; and regex \( matches "(" . You also need to use regex \\ to match "\" (back-slash).

What does '$' mean in regex?

Literal Characters and Sequences For instance, you might need to search for a dollar sign ("$") as part of a price list, or in a computer program as part of a variable name. Since the dollar sign is a metacharacter which means "end of line" in regex, you must escape it with a backslash to use it literally.


1 Answers

You need to use the RegExp constructor instead of a regex literal.

var string = 'asdgghjjkhkh'; var string2 = 'a'; var regex = new RegExp( string2, 'g' ); string.match(regex); 

If you didn't need the global modifier, then you could just pass string2, and .match() will create the regex for you.

string.match( string2 ); 
like image 183
user113716 Avatar answered Sep 24 '22 22:09

user113716