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

where to get list of countries for spinner in android

android

I would like to display a spinner in android in which the user will select a country? I know how to do the spinner but I am wondering about the the country part. Is there some sort of pre-defined l...

How to redefine z-Order in Qt Widget

c++ qt user-interface

i have two Widget having separate implementation. They are ...

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.