Borislav Hadzhiev
Last updated: Oct 26, 2021
Check out my new book
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.
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.
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.
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.
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.