有没有办法在JavaScript中用序列号替换字符串

lmyy7pcs  于 2023-06-28  发布在  Java
关注(0)|答案(4)|浏览(107)

假设我有一个var

var str = 'the @ brown @ fox @ jumped @ over @ the @ fence'

我可以用

var str = 'the 1 brown 2 fox 3 jumped 4 over 5 the 6 fence'

array.from可以帮助

c9qzyr3d

c9qzyr3d1#

Regex方法:

使用replacei,每次查找字符@时都会递增:

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, ''))
mznpcxlj

mznpcxlj2#

您可以使用String#replace和一个跟踪计数的回调函数。

let str = 'the @ brown @ fox @ jumped @ over @ the @ fence';
let i = 0, res = str.replace(/@/g, () => ++i);
console.log(res);

或者,类似于String#replaceAll

let str = 'the @ brown @ fox @ jumped @ over @ the @ fence';
let i = 0, res = str.replaceAll('@', () => ++i);
console.log(res);
ui7jx7zq

ui7jx7zq3#

您可以为索引取一个起始值为1的闭包。

const
    str = 'the @ brown @ fox @ jumped @ over @ the @ fence',
    result = str.replace(/@/g, (i => _ => i++)(1));

console.log(result);
8yparm6h

8yparm6h4#

'the @ brown @ fox @ jumped @ over @ the @ fence'
.split('@')
.reduce((acc,cur,i,s)=> `${acc+cur}${(i+1)!==s.length?`$${i+1}`:''}`,'')

相关问题