在其他字符串中查找字符串出现的次数 - 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
广告
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程语言
C++
C#
MongoDB
MySQL
Javascript
PHP