首页 > 解决方案 > 用数组中的值替换所有出现的子字符串

问题描述

我有两个数组。一个数组包含要搜索的字符,另一个数组包含要替换它们的字符。我想查找字符串中第一个数组中每个项目的所有出现,并将它们替换为第二个数组中的相应项目。

let converted = '';
    let bbCodes = [
      "[code]", "[/code]", "[h1]", "[/h1]"
    ];
    let replacers = [
      "<code>", "</code>", "<h1>", "</h1>"
    ];
    let needsConverted = this.state.txtAreaVal;
    bbCodes.map((code, index) => {
        converted = needsConverted.replace(code, replacers[index]);
        console.log(converted);
    });
    console.log(converted);
  }

输出并不完全符合我的预期。 控制台输出

标签: javascriptarrays

解决方案


问题是您没有跟踪字符串的已更新版本。

  • 在第一次迭代中,它替换了第一个单词([code]to <code>)。然后将此值分配给converted

  • 在第二次迭代中,您替换原始字符串的第二个单词并将结果分配给converted,从而失去上一次迭代的更改。

您不需要另一个变量,您可以重用初始字符串并在每次迭代时不断替换它。

map此外,您可以使用代替使用forEach,这更合适,因为您没有更改数组中的值。

let bbCodes = [
  "[code]", "[/code]", "[h1]", "[/h1]"
];
let replacers = [
  "<code>", "</code>", "<h1>", "</h1>"
];
let needsConverted = 'this is a [code] code [/code] test see [h1] here [/h1]';
bbCodes.forEach((code, index) => {
    // you don't need your other function, you can just reassign your current string to it's new value.
    needsConverted = needsConverted.replace(code, replacers[index]);
});
console.log(needsConverted);


推荐阅读