JavaScript 中仅替换字符串中指定出现次数的字符的函数
javascriptweb developmentfront end technologyobject oriented programming更新于 2026/1/31 16:44:17
我们需要编写一个 JavaScript 函数,该函数将字符串作为第一个参数,将数字(例如 n)作为第二个参数,将字符(例如 c)作为第三个参数。该函数应将第 n 次出现的任何字符替换为提供的字符作为第三个参数,并返回新字符串。
因此,让我们编写该函数的代码 −
示例
其代码为 −
const str = 'This is a sample string';
const num = 2;
const char = '*';
const replaceNthAppearance = (str, num, char) => {
const creds = str.split('').reduce((acc, val, ind, arr) => {
let { res, map } = acc;
if(!map.has(val)){
map.set(val, 1);
if(num === 0){
res += char;
}else{
res += val;
}
}else{
const freq = map.get(val);
if(num - freq === 1){
res += char;
}else{
res += val;
};
map.set(val, freq+1);
};
return { res, map };
}, {
res: '',
map: new Map()
});
return creds.res;
}
console.log(replaceNthAppearance(str, num, char));
输出
控制台中的输出将是 −
This ***a s*mple string
相关文章
有用资源
javascript 参考教程 - 该教程包含有关 javascript 的更多信息:https://www.cainiaomax.com/javascript/

