【发布时间】:2020-01-07 19:13:32
【问题描述】:
我有两个数组。一个数组包含要搜索的字符,另一个数组包含要替换它们的字符。我想在一个字符串中查找第一个数组中每个项目的所有出现,并将它们替换为第二个数组中对应的项目。
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);
}
输出并不完全符合我的预期。
【问题讨论】:
-
stackoverflow.com/questions/1144783/… 回答了主要问题,但您还需要每次编辑编辑的字符串,而不是原始字符串。
-
我看过那个页面,它帮助我走到了这一步。似乎我只需要编辑编辑过的字符串,正如@ASDFGerte 提到的那样。也使用 forEach 而不是 map ,因为正如接受的答案中提到的那样,不需要 map ,因为我没有对数组值做任何事情。谢谢大家的帮助。
标签: javascript arrays