在其他字串中查詢字串出現的次數 - JavaScript


我們要編寫一個 JavaScript 函式,該函式接受兩個字串,並返回第一個字串在第二個字串中出現的次數

假設我們的字串為 −

const main = 'This is the is main is string';

我們必須在上面的“main”字串中查詢以下字串的出現 −

const sub = 'is';

讓我們為此函式編寫程式碼 −

示例

const main = 'This is the is main is string';
const sub = 'is';
const countAppearances = (main, sub) => {
   const regex = new RegExp(sub, "g");
   let count = 0;
   main.replace(regex, (a, b) => {
      count++;
   });
   return count;
};
console.log(countAppearances(main, sub));

輸出

以下是控制檯中顯示的輸出 −

4

更新於: 2020-09-14

78 瀏覽

開啟你的職業生涯

完成課程獲得認證

開始使用
廣告
© . All rights reserved.