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