如何在Javascript

时间:2016-03-10 13:03:21

标签: javascript arrays associative-array

我有以下字符串:

str=["If we go to the park, we will find a big slide!"];

replacer=[["to","a"],["a","un"]];

然后我遍历str并将每次出现的"替换为"与" a"然后每次出现" a"用" un"最终得到:

str=["If we go un the park, we will find un big slide!"];

据我所知,在这个简单的情况下,我可以反转替换器值,但这不是我的选择。无论如何我可以用替换的单词放置某种免责声明或标记,以便当我遍历下一个变量时它会跳过已经替换的单词吗?

谢谢!

2 个答案:

答案 0 :(得分:1)

尝试

var str=["If we go to the park, we will find a big slide!"];
function replacer(str, oldarr, newArr)
{
  oldarr.forEach( function(value,index){

     str = str.replace( new RegExp(value, "g"), newArr[index] );

  } );
  return str;
}
replacer(str[0],["to","a"],["a","un"]);

答案 1 :(得分:0)

您可以按空格将str拆分为数组,然后迭代每个单词,将“used”索引保存到临时数组,不要再次覆盖它,然后将此数组连接回字符串:

var str = ["If we go to the park, we will find a big slide!"];
var replacer = [["to","a"],["a","un"]];
var ar = str[0].split(' ');
var used = [];//temporary array to hold indexes of changes values
replacer.forEach(function(v,k){
    ar.forEach(function(x,i){
        if(used.indexOf(i) < 0){
            if(x == v[0]){
                ar[i] = v[1];
                used.push(i);
            }
        }
    });

});
str = [ar.join(' ')];
console.log(str);

输出:

["If we go a the park, we will find un big slide!"]