Counting dots with javascript returns half

I've written a small function to count the amount of occurrences of a character within a string. It's been working just fine.

Until i tried to count dots, it keeps giving me half the number it should. What am i doing wrong? Am i not escaping the dots in the right manner?

function count(s1, letter) {
    return (s1.length - s1.replace(new RegExp(letter, "g"), '').length) / letter.length;
}

var loc = 'http://www.domain.com/page' // I'm actually using window.location.href in practice.

var someStringWithDots = 'Yes. I want. to. place a. lot of. dots.';

var somestring = 'abbbcdefg';

count(somestring, 'b');
//returns 3 - correct

count(someStringWithDots, '\\.');
//returns 3 - incorrect

count(loc, '\\.');
//returns 1 - incorrect

Answers


Just use .match and you're done:

function count(s1, letter) {
    return ( s1.match( RegExp(letter,'g') ) || [] ).length;
}

count('Yes. I want. to. place a. lot of. dots.','\\.'); //=> 6

[edit] In case no match is found, .length would throw an error. Added a workaround for that (... || [])


Need Your Help

No qualifying bean of type found for dependency

spring java-ee dependency-injection inversion-of-control

I am newbie to Spring framework. I am trying to learn it. But I have all the time the same problem with Ioc. I cant correctly implement it. Please help.

php---which tool i can use to trace a cms source code

php drupal

now, if i want to trace the drupal sourcecode.how and which tool i can use to trace the drupal source code?i want to make a quick walk-through to drupal code. and want to trace it myself,but i don'...