d3020
d3020

Reputation: 537

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.

Upvotes: 0

Views: 581

Answers (4)

Matt Ball
Matt Ball

Reputation: 359776

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

Upvotes: 1

Andy
Andy

Reputation: 2749

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

Upvotes: 0

alex.zherdev
alex.zherdev

Reputation: 24164

Use a RegExpobject:

var x = "0";
strNewDdlVolCannRegion = strNewDdlVolCannRegion.replace(new RegExp("_existing_" + x, "gi"), "existing" + "newCounter"); 

Upvotes: 4

Jerod Venema
Jerod Venema

Reputation: 44632

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.

Upvotes: 1

Related Questions