替换字符串中每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 简短祝福语毛笔字