Friday, February 23, 2024
 Popular · Latest · Hot · Upcoming
98
rated 0 times [  99] [ 1]  / answers: 1 / hits: 140050  / 15 Years ago, thu, july 2, 2009, 12:00:00

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);
}

More From » regex

 Answers
17

tl;dr: Generic Pattern Counter



// THIS IS WHAT YOU NEED
const count = (str) => {
const re = /YOUR_PATTERN_HERE/g
return ((str || '').match(re) || []).length
}


For those that arrived here looking for a generic way to count the number of occurrences of a regex pattern in a string, and don't want it to fail if there are zero occurrences, this code is what you need. Here's a demonstration:





/*
* Example
*/

const count = (str) => {
const re = /[a-z]{3}/g
return ((str || '').match(re) || []).length
}

const str1 = 'abc, def, ghi'
const str2 = 'ABC, DEF, GHI'

console.log(`'${str1}' has ${count(str1)} occurrences of pattern '/[a-z]{3}/g'`)
console.log(`'${str2}' has ${count(str2)} occurrences of pattern '/[a-z]{3}/g'`)





Original Answer



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

[#99206] Friday, June 26, 2009, 15 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
ryans

Total Points: 514
Total Questions: 92
Total Answers: 121

Location: Liberia
Member since Fri, Oct 22, 2021
2 Years ago
;