用javascript计算点数返回一半

dub*_*elj 2 javascript regex string

我写了一个小函数来计算字符串中字符的出现次数.它工作得很好.

直到我试图计算点数,它一直给我一半的数字.我究竟做错了什么?我是不是以正确的方式逃脱了点?

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
Run Code Online (Sandbox Code Playgroud)

Koo*_*Inc 9

只需使用.match即可完成:

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

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

[ 编辑 ]如果未找到匹配项,.length则会抛出错误.
为该(... || [])添加了一种解决方法