Javascript - 从数组中替换重复的字符串

时间:2017-08-30 09:36:50

标签: javascript

我希望我的Javascript使用字符串来执行此操作...

找到" aaa"的第一个实例并用" xxx"替换它。找到" aaa"的第二个实例并用" yyy"替换它。找到" aaa"的第三个实例并用" zzz"替换它。

...并继续这样做,直到它不再找到" aaa"在那个字符串中。

例如,这个字符串......

HELLO aaa WORLD aaa HERE aaa IS aaa SOME aaa RANDOM aaa TEXT aaa FOR aaa TESTING aaa

...将成为这个字符串......

HELLO xxx WORLD yyy HERE zzz IS xxx SOME yyy RANDOM zzz TEXT xxx FOR yyy TESTING zzz

我已经谷歌搜索了关于Javascript替换,数组,循环等的地狱,但我尝试过的一切都没有成功。来自任何Javascript编码器的任何想法吗?

顺便说一句,我不是jQuery用户。所以任何依赖jQuery的代码对我都没用。

5 个答案:

答案 0 :(得分:6)

您可以使用String#replace的替换函数,并将数组作为参数以及替换的起始索引。



function replaceWith(array, i) {
    i = i || 0;
    return function () {
        i %= array.length;
        return array[i++];
    }
}

var string = 'HELLO aaa WORLD aaa HERE aaa IS aaa SOME aaa RANDOM aaa TEXT aaa FOR aaa TESTING aaa';

string = string.replace(/aaa/g, replaceWith(['xxx', 'yyy', 'zzz']));

console.log(string);




答案 1 :(得分:4)

你可以通过以下方式完成

let str = 'HELLO aaa WORLD aaa HERE aaa IS aaa SOME aaa RANDOM aaa TEXT aaa FOR aaa TESTING aaa';

let replacements = ['xxx', 'yyy', 'zzz'], idx = 0;
while(str.match(/aaa/)){
    str = str.replace(/aaa/, replacements[idx]);
    idx = (idx+1)%3;
}

console.log(str);

答案 2 :(得分:3)

var text = "HELLO aaa WORLD aaa HERE aaa IS aaa SOME aaa RANDOM aaa TEXT aaa FOR aaa TESTING aaa";
var set = ["xxx", "yyy", "zzz"] ;
var i = 0;

text = text.replace(/aaa/g, function() {
    return set[i++ % set.length] ;
});

答案 3 :(得分:1)

您可以使用String.prototype.replace()作为第二个参数传递函数来替换字符串:

var replace = ["xxx", "yyy", "zzz"]
var index = 0

str.replace(/aaa/g, function(x) {
    index %= replace.length
    return replace[index++]
})

请注意,此代码可能无法在所有浏览器上运行,因为文档没有说明函数调用的顺序。

如果您想支持所有浏览器,那么您可以使用这样的循环,这可能比使用循环的大多数其他答案更快:

var replace = ["xxx", "yyy", "zzz"]
var index = 0

var result = ""
var copy = str

while (true) {
    var pos = copy.indexOf("aaa")
    if (pos == -1) break

    index %= replace.length
    result += copy.substring(0, pos)
    result += replace[index++]

    // The length of "aaa" is 3.
    copy = copy.substring(pos + 3)
}

答案 4 :(得分:0)

试试这个



function replaceWord(i) {
  const replacedItems = ['xxx', 'yyy', 'zzz']
  var i = i || 0;
  return () => {
    i %= replacedItems.length
    return replacedItems[i++]
  }
}

const input = 'HELLO aaa WORLD aaa HERE aaa IS aaa SOME aaa RANDOM aaa TEXT aaa FOR aaa TESTING aaa'

const result = input.replace(/aaa/g, replaceWord())

console.log(result)