如何在 JavaScript 中计算字符串中特定字符串出现的次数
我们需要编写一个 JavaScript 函数,其中包含两个字符串:str1 和 str2。然后,该函数应计数并返回 str2 在 strl 中出现的次数'
例如,−
count('this is a string', 'is') should return 2;示例
用于此项工作的代码将为 −
const str1 = 'this is a string';
const str2 = 'is';
const countOccurrences = (str1, str2, allowOverlapping = true) => {
str1 += "";
str2 += "";
if (str2.length <= 0) return (str1.length + 1);
var n = 0,
pos = 0,
step = allowOverlapping ? 1 : str2.length;
while (true) {
pos = str1.indexOf(str2, pos);
if (pos >= 0) {
++n;
pos += step;
} else break;
}
return n;
};
console.log(countOccurrences(str1, str2));产出
控制台中的输出将为 −
2
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP