views:

1253

answers:

1

I wanted to write a regex to count the number of spaces/tabs/newline in a chunk of text. So I naively wrote the following:-

numSpaces : function(text) { return text.match(/\s/).length; }

For some unknown reasons it always returns 1. What is the problem with the above statement? I have since solved the problem with the following:-

numSpaces : function(text) { return (text.split(/\s/).length -1); }
+10  A: 

The problem with your initial code is that you are missing the global identifier:

>>> 'hi there how are you'.match(/\s/g).length;
4

Without the g part of the regex it will only match the first occurrence and stop there.

Also note that your regex will count successive spaces twice:

>>> 'hi  there'.match(/\s/g).length;
2

If that is not desirable, you could do this:

>>> 'hi  there'.match(/\s+/g).length;
1
Paolo Bergantino
Yes, (/\s/g) was the one I needed. Thank you lots! =)
wai