-
慕码人2483693
您可以添加一个计数器并通过使用余数进行检查来替换。function replace(string, char, repl, n) { var i = 0; return string.replace(new RegExp(char, 'g'), c => i++ % n ? c : repl);}console.log(replace('x1234,x2345,x3456,x4567,x5678,x6789', 'x', 'd', 2));console.log(replace('x1234,x2345,x3456,x4567,x5678,x6789', 'x', 'd', 3));
-
慕的地8271018
function replaceNth(str, n, newChar) { const arr = str.split(','); return arr.map((item, i) => (i % n === 0) ? item.replace('x', newChar) : item).join(",")}const str = 'x1234,x2345,x3456,x4567,x5678,x6789';// replace for every second string valueconsole.log( replaceNth(str, 2, 'd'));// replace for every third string valueconsole.log( replaceNth(str, 3, 'e'));
-
慕雪6442864
var splittedWords = "x1234,x2345,x3456,x4567,x5678,x6789".split(",")var result = splittedWords.map((element, index) => index % 2 ? element : "d" + element.substring(1))console.log(result.join(","))