只替换 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
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP