I have a string that contains "..." in different places. And a string array with the same amount of words as the number of "...".

I want to replace all occurrences of "..." with the words from the string array.

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"

I have tried this:

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

But that would only change the first occurrence of "...".

推荐答案

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相关问答推荐

按钮未放置在html dis位置

深嵌套的ng-container元素仍然可以在Angular 布局组件中正确渲染内容吗?

如何解决CORS政策的问题

在react js中使用react—router—dom中的Link组件,分配的右侧不能被 destruct ''

如何用拉威尔惯性Vue依赖下拉?

WebGL 2.0无符号整数输入变量

如何从隐藏/显示中删除其中一个点击?

如何将未排序的元素追加到数组的末尾?

在FAQ Accodion应用程序中使用React useState时出现问题

使用类型:assets资源 /资源&时,webpack的配置对象&无效

处理TypeScrip Vue组件未初始化的react 对象

P5.js中的分形树

如何通过Axios在GraphQL查询中发送数组

用于测试其方法和构造函数的导出/导入类

有没有办法更改Chart.js 3.x.x中主要刻度的字体?

Clip-Path在网页浏览器(Mozilla、Edge、Chrome)上不能正常工作,但在预览版Visual Code Studio HTML、CSS、JS上却能很好地工作

Rails 7:在不使用导入映射的情况下导入Java脚本

当一条路由在Reaction路由中命中时,如何有条件地渲染两个组件或更改两个插座?

react :图表负片区域不同 colored颜色

观察子组件中的@Output事件emits 器?