Simple Javascript replace with a loop

2019-07-11 04:35发布

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.

4条回答
欢心
2楼-- · 2019-07-11 05:05

try using this:

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

instead of this:

var x = /'{' + i + '}'/g;
查看更多
放我归山
3楼-- · 2019-07-11 05:11

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;
}
查看更多
神经病院院长
4楼-- · 2019-07-11 05:14

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/

查看更多
对你真心纯属浪费
5楼-- · 2019-07-11 05:27

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].

查看更多
登录 后发表回答