Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript - count spaces before first character of a string

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'; 
like image 780
K3NN3TH Avatar asked Sep 13 '14 13:09

K3NN3TH


People also ask

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.

How do you isolate the first character in a string JavaScript?

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] .

How do you get the first word before a space in JavaScript?

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.

Do you count spaces in a 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.


1 Answers

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|$/) 
like image 128
folkol Avatar answered Sep 22 '22 03:09

folkol