regex - Counting dots with javascript returns half -
i've written small function count amount of occurrences of character within string. it's been working fine.
until tried count dots, keeps giving me half number should. doing wrong? not escaping dots in 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 using window.location.href in practice. var somestringwithdots = 'yes. 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
just use .match , you're done:
function count(s1, letter) { return ( s1.match( regexp(letter,'g') ) || [] ).length; } count('yes. want. to. place a. lot of. dots.','\\.'); //=> 6
[edit] in case no match found, .length
throw error.
added workaround (... || []
)
Comments
Post a Comment