count how many times a string appears within another string
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.
精彩评论