我有两个数组。一个数组包含要搜索的字符,另一个数组包含要替换它们的字符。我想找到字符串中第一个数组中每个项目的所有出现,并将它们替换为第二个数组中相应的项目。
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);
}
输出并不完全符合我的预期。
最佳答案
问题是您没有跟踪字符串的已更新版本。
在第一次迭代时,它替换第一个单词(
[code]
到<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);
关于javascript - 将所有出现的子字符串替换为数组中的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59634689/