只替換 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

更新於: 19-Oct-2020

71 次瀏覽

開啟您的職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.