Summary: in this tutorial, you’ll learn how to use the JavaScript String trimStart()
method to remove whitespace from the beginning of a string.
Introduction to the JavaScript string trimStart() method
To remove whitespace from the beginning of a string, you use the trimStart()
method:
let newString = str.trimStart();
Code language: JavaScript (javascript)
The trimStart()
method returns a new string from the original string (str
) with the leading whitespace removed.
Note that the trimStart()
method returns a new string and doesn’t change the original string.
The following characters are the whitespace characters in JavaScript:
- A space character (
' '
) - A tab character (
\t
) - A carriage return character (
\r
) - A new line character. (
\n
) - A vertical tab character. (
\v
) - A form feed character. (
\f
)
Note that to remove trailing whitespace from a string, you use the trimEnd() method.
JavaScript string trimStart() method examples
The following example shows how to use the trimStart()
to remove whitespace from the beginning of a string:
const str = ' JavaScript Tutorial ';
const result = str.trimStart();
console.log({ str });
console.log({ result });
Code language: JavaScript (javascript)
Output:
{str: ' JavaScript Tutorial '}
{result: 'JavaScript Tutorial '}
Code language: JavaScript (javascript)
Alias
The trimLeft()
method is an alias for the trimStart()
method, therefore, they have the same functionality.
In practice, it’s recommended that you use the trimStart()
method because of the following reasons:
- Standardization: The
trimStart()
method is part of ECMAScript, while thetrimLeft()
is a non-standard method. This means that thetrimStart()
is more likely supported across different JavaScript runtimes. - Consistency: The
trimStart()
method is consistent with other string methods like padStart(), making the code more consistent and easier to understand.
Summary
- The
trimStart()
returns a new string from the original string with the leading whitespace characters removed. - The
trimLeft()
method is an alias for thetrimStart()
method.