What is the best way to count how many spaces before the fist character of a string?
str0 = 'nospaces even with other spaces still bring back zero'; str1 = ' onespace do not care about other spaces'; str2 = ' twospaces';
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.
You should use the charAt() method, at index 0, to select the first character of the string. NOTE: charAt is preferable than using [ ] (bracket notation) as str. charAt(0) returns an empty string ( '' ) for str = '' instead of undefined in case of ''[0] .
To get the first word of a string:Call the split() method passing it a string containing an empty space as a parameter. The split method will return an array containing the words in the string. Access the array at index 0 to get the first word of the string.
The length of a string is the number of characters in the string. Thus, "cat" has length 3, "" has length 0, and "cat " has length 4. Notice that spaces count in the length, but the double quotes do not. If we have escape sequences in the alphabet, then they count as one character.
Use String.prototype.search
' foo'.search(/\S/); // 4, index of first non whitespace char
EDIT: You can search for "Non whitespace characters, OR end of input" to avoid checking for -1.
' '.search(/\S|$/)
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