字串在另一個 JavaScript 中出現的次數


我們需要編寫一個 JavaScript 函式,這個函式需要輸入兩個字串,然後返回 str1 在 str2 中出現的次數。

示例

程式碼如下 −

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

更新日期: 14-Oct-2020

178 次瀏覽

開啟 你的職業生涯

完成課程獲得認證

開始
廣告
© . All rights reserved.