如何用js中的数组节点替换多字符串

时间:2010-05-13 08:21:55

标签: javascript arrays

我在这里工作,我不知道该怎么做。 我在这里有一个字符串:

<div class="demotext">
   <p>this is demo string i demo want to demo use</p>
</div>

我为demo创建了数组变量:

var demoarray = new array('a','b','c');

现在我想在数组节点的字符串中替换'demo',按照'demo'一个更改为'a','demo'两个更改为'b'....

2 个答案:

答案 0 :(得分:4)

var string = 'this is demo string i demo want to demo use';
var demoarray = ['a','b','c'];

for(i=0; i < demoarray.length; i++){
    string = string.replace('demo',demoarray[i] );
}

alert(string) // "this is a string i b want to c use"

答案 1 :(得分:0)

function sequential_replace(str, replacementRx, arr) {
   var i = 0;
   return str.replace(replacementRx, function() {
      return arr[i++];
   });
}

return sequential_replace("this is demo string i demo want to demo use",
                          /demo/g, ['a', 'b', 'c']);