Remove the leading Spaces from a String in JavaScript

avatar

Borislav Hadzhiev

Tue Oct 26 20211 min read

banner

Photo by Jeremy Bishop

Remove the leading Spaces from a String #

Use the trimStart() method to remove the leading spaces from a string. The trimStart method returns a new string representing the original string stripped of any leading spaces.

index.js
const str = ' hello '; // ๐Ÿ‘‡๏ธ remove leading spaces const withoutLeadingSpaces = str.trimStart(); console.log(withoutLeadingSpaces); // ๐Ÿ‘‰๏ธ "hello " // ๐Ÿ‘‡๏ธ remove both leading and trailing spaces const withoutLeadingAndTrailing = str.trim(); console.log(withoutLeadingAndTrailing); // ๐Ÿ‘‰๏ธ "hello"

We used the String.trimStart method to remove the leading spaces from a string.

The trimStart method does not change the original string, instead it returns a new string stripped of any leading whitespace.

If the string contains no leading spaces, a copy of it gets returned from trimStart and no error is thrown.

index.js
const str = 'example'.trimStart(); console.log(str); // ๐Ÿ‘‰๏ธ "example"

When the trimStart method is used on a string that contains leading spaces, the new string has a new length.

index.js
const str = ' example'; console.log(str.length); // ๐Ÿ‘‰๏ธ 10 const withoutLeadingSpaces = str.trimStart(); console.log(withoutLeadingSpaces.length); // ๐Ÿ‘‰๏ธ 7

If you want to remove the leading and trailing space from a string, use the trim method instead.

Further Reading #

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee