31

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';
4
  • Out of curiosity, why do you want to count the spaces? You know about trim right? Commented Sep 13, 2014 at 14:00
  • i have a text box for quick edit of json string and i need to know how many spaces before the string starts to figure out where it is in the object Commented Sep 13, 2014 at 14:01
  • You could use the regex /^\s+/ and count using str0.match(/^\s+/)[0].length Commented Sep 13, 2014 at 14:01
  • Try to use jQuery and add ltrim functions in combination with suggested solution below. A reference link: somacon.com/p355.php Commented Sep 13, 2014 at 14:03

6 Answers 6

66

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|$/)
Sign up to request clarification or add additional context in comments.

6 Comments

I like this. It does require that at least one non-whitespace char appears, but it's nice and clean. I suggest this addition: ' '.search(/\S|$/) which will account for strings which do not have a non-whitespace char.
Yeah, it will return -1 if there is no match for \S.
With or without my addition, depending on the OP's needs, I like this answer better than my own. Good thinking.
Yeah, that is a nice way to handle it. I'll update the answer.
there will be no case of all white space but still nice to know
|
10

Using the following regex:

/^\s*/

in String.prototype.match() will result in an array with a single item, the length of which will tell you how many whitespace chars there were at the start of the string.

pttrn = /^\s*/;

str0 = 'nospaces';
len0 = str0.match(pttrn)[0].length;

str1 = ' onespace do not care about other spaces';
len1 = str1.match(pttrn)[0].length;

str2 = '  twospaces';
len2 = str2.match(pttrn)[0].length;

Remember that this will also match tab chars, each of which will count as one.

3 Comments

have to wait 6 min to answer
Take a look at my comment on @folkol's answer, and then accept that answer. I like that solution better. You can determine whether you need my addition or not depending upon your circumstances and needs, but overall it's cleaner.
ya, finding index was pretty slick indeed. I'll never look at a string the same.
9

You could use trimLeft() as follows

myString.length - myString.trimLeft().length

Proof it works:

let myString = '       hello there '

let spacesAtStart = myString.length - myString.trimLeft().length

console.log(spacesAtStart)

See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/TrimLeft

1 Comment

If you need to support IE, trimLeft is not an option. Just use the regex solutions above. Otherwise, this is awesome.
5
str0 = 'nospaces';
str1 = ' onespace do not care about other spaces';
str2 = '  twospaces';

arr_str0 = str0.match(/^[\s]*/g);
count1 = arr_str0[0].length;
console.log(count1);

arr_str1 = str1.match(/^[\s]*/g);
count2 = arr_str1[0].length;
console.log(count2);

arr_str2 = str2.match(/^[\s]*/g);
count3 = arr_str2[0].length;
console.log(count3);

Here: I have used regular expression to count the number of spaces before the fist character of a string.

^ : start of string.
\s : for space
[ : beginning of character group
] : end of character group

Comments

0
str.match(/^\s*/)[0].length

str is the string.

Comments

0

A bit late, but just for giving a different answer

let myString     = "     string";
let count_spaces = myString.length - myString.trim().length;

Note that if the string has spaces at the end will also be added.

2 Comments

Good idea. But its explicit asked to count spaces at the beginning of the string. So why not use trimStart() instead of trim()?
Yes! you are right It can also be used, as also trimEnd() for other cases, ofc.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.