Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
178
rated 0 times [  184] [ 6]  / answers: 1 / hits: 71563  / 13 Years ago, sat, august 13, 2011, 12:00:00

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;

More From » regex

 Answers
36

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

[#90627] Friday, August 12, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
annie

Total Points: 483
Total Questions: 97
Total Answers: 107

Location: Belarus
Member since Sat, Jul 18, 2020
4 Years ago
;