最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

regex - Simple Javascript replace with a loop - Stack Overflow

programmeradmin1浏览0评论

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.

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.

Share Improve this question edited Jul 12, 2012 at 6:31 Lion 19k22 gold badges82 silver badges111 bronze badges asked Jul 12, 2012 at 6:25 Alex GuerinAlex Guerin 2,38610 gold badges37 silver badges55 bronze badges 1
  • 2 Don't use for... in... for arrays – Andreas Commented Jul 12, 2012 at 6:35
Add a comment  | 

4 Answers 4

Reset to default 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].

try using this:

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

instead of this:

var x = /'{' + i + '}'/g;

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/

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;
}
发布评论

评论列表(0)

  1. 暂无评论