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.
-
Can you provide simple input - simple output, what you've given us so far is just jibber-jabberant– ant2010年03月26日 14:59:40 +00:00Commented Mar 26, 2010 at 14:59
-
@c0mrade: his question was clear enough.Matt Ball– Matt Ball2010年03月26日 15:04:58 +00:00Commented Mar 26, 2010 at 15:04
-
@Bears will eat you it was to you , not to me :Dant– ant2010年03月26日 15:35:23 +00:00Commented Mar 26, 2010 at 15:35
-
FYI if you can use the solution provided by @Matt, I benched the constructor against the literal. Constructor took 1600-1800% longer over 1000000 iterations. I had no idea the overhead was so high.fncomp– fncomp2011年02月05日 09:45:07 +00:00Commented Feb 5, 2011 at 9:45
4 Answers 4
Use a RegExpobject:
var x = "0";
strNewDdlVolCannRegion = strNewDdlVolCannRegion.replace(new RegExp("_existing_" + x, "gi"), "existing" + "newCounter");
1 Comment
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.
Comments
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
Comments
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")