JavaScript replace()
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.
Use a RegExp
object:
var x = "0";
strNewDdlVolCannRegion = strNewDdlVolCannRegion.replace(new RegExp("_existing_" + x, "gi"), "existing" + "newCounter");
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.
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
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")
精彩评论