我有一个在不同位置包含“...”的字符串。 以及一个与“...”的字数相同的字符串数组。
我想用字符串数组中的单词替换所有出现的“...”。
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/