7

I'm try to replace all occurances wihtin a string with the array index value as below.

var str = '<a href="{0}" title="{1}">{1}</a>';
var params= [];
params.push('Url', 'TitleDisplay');
for (i in params) {
 var x = /'{' + i + '}'/g;
 str = str.replace(x, params[i]);
}

No matter what I do, I cannot seem to get it to work. Dropping the '/g' works with one match, but not all. I know this is basic but for the lide of me I cannot get it to work.

Lion
19.1k22 gold badges83 silver badges111 bronze badges
asked Jul 12, 2012 at 6:25
1
  • 2
    Don't use for... in... for arrays Commented Jul 12, 2012 at 6:35

4 Answers 4

8

Fiddle here

Code:

var rx = /{([0-9]+)}/g;
str=str.replace(rx,function(0,ドル1ドル){return params[1ドル];});

The replace method loops through the string (because of /g in the regex) and finds all instances of {n} where n is a number. 1ドル captures the number and the function replaces {n} with params[n].

answered Jul 12, 2012 at 7:44
Sign up to request clarification or add additional context in comments.

Comments

2

try using this:

var x = new RegExp("\\{" + i + "\\}", "g");

instead of this:

var x = /'{' + i + '}'/g;
answered Jul 12, 2012 at 6:36

Comments

2

You can build a regexp object if you need it to be dynamic

var str = '<a href="{0}" title="{1}">{1}</a>';
var params= [];
params.push('Url', 'TitleDisplay');
for (var i = 0; i < params.length; i++) {
 var x = new RegExp('(\\{'+i+'\\})', 'g');
 str = str.replace(x, params[i]);
}
alert(str);
​

http://jsfiddle.net/LByBT/

answered Jul 12, 2012 at 6:36

Comments

1

How about this if you would like to skip a regex solution ..

function replaceAllOccurrences(inputString, oldStr, newStr) 
{
 while (inputString.indexOf(oldStr) >= 0)
 {
 inputString = inputString.replace(oldStr, newStr);
 }
 return inputString;
}
answered Aug 7, 2014 at 19:29

2 Comments

Can you share your code and the input strings you use - for me I use this successfully across a variety of projects
@emotality that is because probably you are replacing a string with the same string with something in front of or at the end of it

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.