views:

61

answers:

4

I'm trying to use the replace function in JavaScript and have a question.

strNewDdlVolCannRegion = strNewDdlVolCannRegion.replace(/_existing_0/gi,
    "_existing_" + "newCounter");

That works.

But I need to have the "0" be a variable.

I've tried: _ + myVariable +/gi and also tried _ + 'myVariable' + /gi

Could someone lend a hand with the syntax for this, please. Thank you.

+1  A: 

You need to use a RegExp object. That'll let you use a string literal as the regex, which in turn will let you use variables.

jvenema
+4  A: 

Use a RegExpobject:

var x = "0";
strNewDdlVolCannRegion = strNewDdlVolCannRegion.replace(new RegExp("_existing_" + x, "gi"), "existing" + "newCounter"); 
neutrino
Thank you. The example helped here and was exactly what I needed. Thanks again.
d3020
A: 

If you use the RegExp constructor, you can define your pattern using a string like this:

var myregexp = new RegExp(regexstring, "gims") //first param is pattern, 2nd is options

Since it's a string, you can do stuff like:

var myregexp = new RegExp("existing" + variableThatIsZero, "gims")

Andy
Thank you as well for the example. Helpful. Thanks.
d3020
A: 

Assuming you mean that you want the zero to be any single-digit number, this should work:

y = x.replace(/_existing_(?=[0-9])/gi, "existing" + "newCounter");

It looks like you're trying to actually build a regex literal with string concatenation - that won't work. You need to use the RegExp() constructor form instead, in order to inject a specific variable into the regex: https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Objects/RegExp

Matt Ball