开发者

count how many times a string appears within another string

开发者 https://www.devze.com 2023-01-30 17:59 出处:网络
I have a string which poin开发者_StackOverflow社区ts to a CSS file ../../css/style.css I want to find out how many

I have a string which poin开发者_StackOverflow社区ts to a CSS file

../../css/style.css

I want to find out how many

../

are within the string.

How do I get this with JavaScript?


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

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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号