K3NN3TH
K3NN3TH

Reputation: 1496

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';

Upvotes: 30

Views: 20503

Answers (6)

David Cervera
David Cervera

Reputation: 1

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.

Upvotes: 0

danday74
danday74

Reputation: 56966

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

Upvotes: 9

iNikkz
iNikkz

Reputation: 3819

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

Upvotes: 5

folkol
folkol

Reputation: 4883

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|$/)

Upvotes: 65

maowtm
maowtm

Reputation: 2012

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

str is the string.

Upvotes: 0

JAAulde
JAAulde

Reputation: 19560

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.

Upvotes: 10

Related Questions