Reputation: 1850
I have a string and i need to check number of occurrence of character
var obj = "str one,str two,str three,str four";
i am trying some thing like this :-
console.log(("str one,str two,str three,str four".match(new RegExp("str", "g")) || []).length);
It returns 4
this is working fine,
But my condition is i don't have to check str three from that string, so output should be 3
Help me to find the solution of this issue.
Thanks
Upvotes: 1
Views: 66
Reputation: 40394
var string = "str1,str2,str3,str4";
var count = (string.match(/str[0-24-9]/g) || []).length;
console.log(count); //3
var string = "str one,str two,str three,str four";
var count = (string.match(/str (?!three)/g) || []).length;
console.log(count); //3
(?!three) - Negative lookahead (?!)
, which specifies a group that cannot match after the main expression.
Upvotes: 3
Reputation: 5224
Split your string as an array, and then count the number of elements that
Something like this?
var numMatches = obj.split(',').filter(function(str) {
return el !== 'str three' && el.match(/str/);
}).length
Or if you want to have fun with regexps, you can use a negative look ahead!
var numMatches = obj.match(/(?!str three)str/g).length;
Upvotes: 0