Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript - Use variable in string match

I found several similar questions, but it did not help me. So I have this problem:

var xxx = "victoria"; var yyy = "i"; alert(xxx.match(yyy/g).length); 

I don't know how to pass variable in match command. Please help. Thank you.

like image 729
mesnicka Avatar asked Jul 03 '10 21:07

mesnicka


People also ask

Can I use variable in regex?

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

How do you embed variables expressions in a string?

Variables in Strings with Template Literals One special feature of the template literal feature is the ability to include expressions and variables within a string. Instead of having to use concatenation, we can use the ${} syntax to insert a variable.

What does .match do in JavaScript?

The match() method returns an array with the matches. The match() method returns null if no match is found.

How do you match strings?

Using String.equalsIgnoreCase() method compares two strings irrespective of the case (lower or upper) of the string. This method returns true if the argument is not null and the contents of both the Strings are same ignoring case, else false.


1 Answers

Although the match function doesn't accept string literals as regex patterns, you can use the constructor of the RegExp object and pass that to the String.match function:

var re = new RegExp(yyy, 'g'); xxx.match(re); 

Any flags you need (such as /g) can go into the second parameter.

like image 53
Chris Hutchinson Avatar answered Sep 17 '22 17:09

Chris Hutchinson