替换字符串中每n个字符的实例-JavaScript
我们需要编写一个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
热门推荐
10 毛笔哥哥结婚祝福语简短
11 向国庆送祝福语简短
12 建队节祝福语简短
13 朋友喜得外孙简短祝福语
14 小店营业的祝福语简短
15 餐饮生日祝福语简短独特
16 鲜花英语祝福语卡片简短
17 男朋友暴富祝福语简短
18 婶婶拜年祝福语大全简短