How to count spaces before first character of a string with JavaScript?

Sometimes, we want to count spaces before first character of a string with JavaScript.

In this article, we’ll look at how to count spaces before first character of a string with JavaScript.

How to count spaces before first character of a string with JavaScript?

To count spaces before first character of a string with JavaScript, we can use the JavaScript string’s search method.

For instance, we write:

const index = '    foo'.search(/S/);
console.log(index)

We call search with a regex to match all non-whitespace characters.

Therefore, index is the index of first character that’s not a space.

index is 4, so any character before index 4 is a space, and so there’re 4 spaces before 'foo'.

Conclusion

To count spaces before first character of a string with JavaScript, we can use the JavaScript string’s search method.