0

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.

Dinah
54.3k32 gold badges135 silver badges149 bronze badges
asked Mar 26, 2010 at 14:57
4
  • Can you provide simple input - simple output, what you've given us so far is just jibber-jabber Commented Mar 26, 2010 at 14:59
  • @c0mrade: his question was clear enough. Commented Mar 26, 2010 at 15:04
  • @Bears will eat you it was to you , not to me :D Commented 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. Commented Feb 5, 2011 at 9:45

4 Answers 4

4

Use a RegExpobject:

var x = "0";
strNewDdlVolCannRegion = strNewDdlVolCannRegion.replace(new RegExp("_existing_" + x, "gi"), "existing" + "newCounter"); 
answered Mar 26, 2010 at 15:00
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you. The example helped here and was exactly what I needed. Thanks again.
1

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.

answered Mar 26, 2010 at 15:00

Comments

1

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

answered Mar 26, 2010 at 15:03

Comments

0

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

answered Mar 26, 2010 at 15:01

1 Comment

Thank you as well for the example. Helpful. Thanks.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.