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.
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() .
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.
The match() method returns an array with the matches. The match() method returns null if no match is found.
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.
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.
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