Er KK Chopra
Er KK Chopra

Reputation: 1850

how to Count the number of occurrences of a character in a string but not one of them?

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

Answers (2)

Marcos Casagrande
Marcos Casagrande

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

Eloims
Eloims

Reputation: 5224

Split your string as an array, and then count the number of elements that

  1. Are not 'str three'
  2. Match your regexp

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

Related Questions