javascript - 如何用数组中的字符串替换所有出现的字符串

标签 javascript string

我有一个在不同位置包含“...”的字符串。 以及一个与“...”的字数相同的字符串数组。

我想用字符串数组中的单词替换所有出现的“...”。

let stringToReplace = "I want an ... that I get from the ..."
let stringArray = ["apple","shop"]

result = "I want an apple that I get from the shop"

我已经尝试过这个:

let result = stringToReplace;
for (let i = 0; i < stringArray.length; i++) {
   let inloc = stringArray[i];
   result = result.replace("...", inloc);
}

但这只会改变第一次出现的“...”。

最佳答案

let s = "I want an ... that I get from the ..."
let r = ["apple","shop"]

console.log(s.split('...').flatMap((e,i)=>[e,r[i]]).join(''));

关于javascript - 如何用数组中的字符串替换所有出现的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74510061/

相关文章:

javascript - 向特定用户广播事件(socket.io、redis、node)

javascript - IE10 navigator.userAgent 脚本不起作用

javascript - Angular Material : how to realize a list like on docs website?

javascript - 替换以特定文本开头的元素的文本

java - 字符串作为 switch 语句

java - 字符串到 Json 转换器给出无效的 Json 值

javascript - 添加指向动态 Canvas 的链接

python - 拆分带有附加空格的 Python 字符串(句子)

javascript - 如何使用 Adob​​e XI Pro 根据 PDF 中的短语删除页面?

c++ - C++ 中的字符串数组无法正常工作?