假设我有以下字符串:
Would you like some tea?
我只想将第二次和第三次出现的
o
替换为0
,所以它变成:
Would y0u like s0me tea?
或者也许我想替换第一次和最后一次出现的情况,如下所示:
W0ould you like s0me tea?
知道如何实现这一目标吗?
任何帮助表示赞赏!
function replaceSpecificOccurrences(str, charachterToReplace, replacementChar, occurrences) {
let count = 0;
return str.split('').map(char => {
if (char === charachterToReplace) {
count++;
if (occurrences.includes(count)) {
return replacementChar;
}
}
return char;
}).join('');
}
const originalString = "Would you like some tea?";
const newString = replaceSpecificOccurrences(originalString, 'o', '0', [2, 3]);
console.log(newString);
这是我能想到的最好的了