javascript - 用数组中的值替换所有出现的子字符串
问题描述
我有两个数组。一个数组包含要搜索的字符,另一个数组包含要替换它们的字符。我想查找字符串中第一个数组中每个项目的所有出现,并将它们替换为第二个数组中的相应项目。
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]
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);
推荐阅读
- baqend - 无法在 Plesk 上打开 Speed Kit
- docker - Docker下matplotlib窗口中的奇怪文本
- android - 在没有序列化程序的对象上使用 JSON.stringify 需要标记为实验性
- python - 是否可以在 python 控制台中自动跳转到帮助函数输出的开头?
- python - 将字典变量传递给自定义模块
- c# - 获取多个相同类型的正在运行的 COM 对象
- svn - svn 忽略文件不适用于 svn add
- android - 使用 FusedLocation 停止位置更新
- c# - GetType("UnityEngine.Debug").GetMethod("Log", new Type[] { typeof(string) }); 在即时模式面板中生成错误,而不是在代码中
- javascript - 如何避免在生成大量 html 元素时冻结浏览器