let str = 'the @ brown @ fox @ jumped @ over @ the @ fence';
let i=0;
console.log(str.replace(/@/g, _ => ++i))
for-loop方式
let str = 'the @ brown @ fox @ jumped @ over @ the @ fence';
let arr = str.split('@');//[ "the ", " brown ", " fox ", " jumped ", " over ", " the ", " fence" ]
let result = arr[0];
for (let i = 1; i < arr.length; i++) {
result += i + arr[i];
}
console.log(result)
reduce方法:
let str = 'the @ brown @ fox @ jumped @ over @ the @ fence';
let arr = str.split('@');
console.log(arr
.reduce((acc, curr, i) =>
acc + (i !== 0 ? i : '') + curr, ''))
4条答案
按热度按时间c9qzyr3d1#
Regex
方法:使用replace和
i
,每次查找字符@
时都会递增:for-loop
方式reduce
方法:mznpcxlj2#
您可以使用
String#replace
和一个跟踪计数的回调函数。或者,类似于
String#replaceAll
:ui7jx7zq3#
您可以为索引取一个起始值为1的闭包。
8yparm6h4#