如何仅替换字符串中的特定匹配项?

问题描述 投票:0回答:1

假设我有以下字符串:

Would you like some tea?

我只想将第二次和第三次出现的

o
替换为
0
,所以它变成:

Would y0u like s0me tea?

或者也许我想替换第一次和最后一次出现的情况,如下所示:

W0ould you like s0me tea?

知道如何实现这一目标吗?

任何帮助表示赞赏!

javascript string substring
1个回答
-1
投票
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);

这是我能想到的最好的了

© www.soinside.com 2019 - 2024. All rights reserved.