字符串在另一个 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
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
安卓
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP