Skip to content Skip to sidebar Skip to footer

Counting A Spectific Character In A String

I have a string file123,file456,file789 I want to count the number of time ',' is in this string for example for this string the answer should be 2

Solution 1:

Simple regex will give you the length:

var str = "file123,file456,file789";
var count = str.match(/,/g).length;

Solution 2:

There are lots of ways you can do this, but here's a few examples :)

1.

"123,123,123".split(",").length-1

2.

("123,123,123".match(/,/g)||[]).length

Solution 3:

You can use RegExp.exec() to keep memory down if you're dealing with a big string:

var re = /,/g,
str = 'file123,file456,file789',
count = 0;

while (re.exec(str)) {
    ++count;
}

console.log(count);

Demo - benchmark comparison

The performance lies about 20% below a solution that uses String.match() but it helps if you're concerned about memory.

Update

Less sexy, but faster still:

var count = 0,
pos = -1;

while ((pos = str.indexOf(',', pos + 1)) != -1) {
  ++count;
}

Demo

Solution 4:

It is probably quicker to split the string based on the item you want and then getting the length of the resulting array.

var haystack = 'file123,file456,file789';
var needle = ',';
var count = haystack.split(needle).length - 1;

Solution 5:

Since split has to create another array, I would recommend writing a helper function like this

functioncount(originalString, character) {
    var result = 0, i;
    for (i = 0; i < originalString.length; i += 1) {
        if (character == originalString.charAt(i)) {
            result +=1;
        }
    }
    return result;
}

Post a Comment for "Counting A Spectific Character In A String"