2

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
dubbelj
  • 1,150
  • 4
  • 15
  • 23
  • Have you tried not escaping periods at all and just doing count(loc, '.') ? – DGH Dec 01 '10 at 08:31
  • I have, and because a dot matches all characters in regExp it wil return the length of the entire string – dubbelj Dec 01 '10 at 08:43

4 Answers4

9

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 (... || [])

KooiInc
  • 119,216
  • 31
  • 141
  • 177
2

That's because letter.length is 2 and you divide the result by that.

Try to remove the escape characters from the string letter before you count the size or, even better, escape the letter in count().

Aaron Digulla
  • 321,842
  • 108
  • 597
  • 820
  • However i see that this the explanation for the problem. I don't know how to dynamically escape the dot. escape() unescape() doesn't work for this it seems. – dubbelj Dec 01 '10 at 08:44
  • 1
    See this question: http://stackoverflow.com/questions/280793/case-insensitive-string-replacement-in-javascript – Aaron Digulla Dec 01 '10 at 10:01
0

You're dividing by letter.length but that does not use the completely un-escaped version of your string, therefore you're diving in fact by two.

'\\.' un-esacped is \.
`\\.`.length is 2
Ivo Wetzel
  • 46,459
  • 16
  • 98
  • 112
0

Try this.

function count(s1, letter) {
var result = split(s1,letter);
if(result && result.length >0)
    return result.length - 1;
else
 return 0;
}
WaiLam
  • 997
  • 1
  • 9
  • 15