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....
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.
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.
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.
" a".match(/^\s{0,2}/)[0].length
This regex matches between 0 and 2 whitespace characters at the beginning of a string.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With