替换字符串中每个第 n 个字符实例 - JavaScript

javascriptweb developmentfront end technologyobject oriented programming更新于 2025/12/7 10:52: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

相关文章


有用资源