Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript regex to count whitespace characters

Can I use a javascript regex to count the number of whitespace characters before the first text character in the string? I only care if there are 0, 1, and 2+.

My current working solution is to have three regexes and just use match to determine the 0,1, or 2+ category(separate pattern for each), but Im looking for a more elegant solution.

Is it even possible to count patterns with regex? I could use a non-greedy grouping and count the length I guess....

like image 641
hvgotcodes Avatar asked Jul 29 '11 00:07

hvgotcodes


People also ask

How to count space in regex?

However, since we're talking about Regex, there can be other quick ways to count spaces. We know that we can do “search and replace” using the String. replaceAll() method. Therefore, if we replace all non-space characters in the input string with an empty string, all spaces from the input will be the result.

How do I count spaces in Javascript?

To count the spaces in a string:Use the split() method to split the string on each space. Access the length property on the array and subtract 1. The result will be the number of spaces in the string.

What is white space in regex?

The most common forms of whitespace you will use with regular expressions are the space (␣), the tab (\t), the new line (\n) and the carriage return (\r) (useful in Windows environments), and these special characters match each of their respective whitespaces.


1 Answers

"     a".match(/^\s{0,2}/)[0].length

This regex matches between 0 and 2 whitespace characters at the beginning of a string.

like image 88
SLaks Avatar answered Oct 13 '22 20:10

SLaks