仅在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
热门推荐
3 短祝福语简短暖心
10 女生 节日祝福语简短大气
11 朋友花篮开业祝福语简短
12 20岁简短生日祝福语
13 国庆中秋祝福语简短搞笑
14 朋友孩子考试祝福语简短
15 情人表白祝福语简短大气
16 三八简短祝福语给婆婆
17 奶奶生日感恩祝福语简短
18 喜事敬酒祝福语简短精辟