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

时间:2021-03-30 23:57:59

I have a string which points to a CSS file

我有一个指向CSS文件的字符串

../../css/style.css

I want to find out how many

我想知道有多少

../

are within the string.

在字符串内。

How do I get this with JavaScript?

我如何使用JavaScript获得此功能?

2 个解决方案

#1


11  

You can use match with a regular expression, and get the length of the resulting array:

您可以使用与正则表达式的匹配,并获取结果数组的长度:

var str = "../../css/style.css";

alert(str.match(/\.\.\//g).length);
//-> 2

Note that . and / are special characters within regular expressions, so they need to be escaped as per my example.

注意 。和/是正则表达式中的特殊字符,因此需要根据我的示例进行转义。

#2


14  

You don't need a regex for this simple case.

对于这个简单的案例,您不需要正则表达式。

var haystack = "../../css/style.css";
var needle   = "../";
var count    = haystack.split(needle).length - 1;

#1


11  

You can use match with a regular expression, and get the length of the resulting array:

您可以使用与正则表达式的匹配,并获取结果数组的长度:

var str = "../../css/style.css";

alert(str.match(/\.\.\//g).length);
//-> 2

Note that . and / are special characters within regular expressions, so they need to be escaped as per my example.

注意 。和/是正则表达式中的特殊字符,因此需要根据我的示例进行转义。

#2


14  

You don't need a regex for this simple case.

对于这个简单的案例,您不需要正则表达式。

var haystack = "../../css/style.css";
var needle   = "../";
var count    = haystack.split(needle).length - 1;