Adam
Adam

Reputation: 675

Javascript RegEx String with Variable

I have the following RegEx that works:

var expression = /s\[0\]\[children\]\[.*?\]\[/g;
var replace_string = "s[" + count + "][children][" + subCount + "]";
$input.attr('name', $input.attr('name').replace(expression, replace_string));

Now I am wanting to replace the 0 in the above regex with a variable, "count". I have read up that it needs to be turned into a string, which I have done:

var expression = "/s\\[" + count + "\\]\\[children\\]\\[.*?\\]/g";

But that doesn't want to work for some reason, what am I doing wrong?

Cheers

Upvotes: 1

Views: 55

Answers (1)

Avinash Raj
Avinash Raj

Reputation: 174874

You need to use RegExp constructor whenever you want to call a variable from regex.

var expression = new RegExp("s\\[" + count + "\\]\\[children\\]\\[.*?\\]", "g");

Upvotes: 2

Related Questions