一个字符串在另一个 JavaScript 中出现的次数

javascriptweb developmentfront end technologyobject oriented programming更新于 2026/1/25 5:32:17

我们需要编写一个 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

相关文章


有用资源