Remove the leading Spaces from a String in JavaScript

avatar

Borislav Hadzhiev

Last updated: Oct 26, 2021

banner

Check out my new book

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 #

Use the search field on my Home Page to filter through my more than 3,000 articles.