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