JavaScript Tutorials

JavaScript String trimStart()
Syntax & Examples

String.trimStart() method

The trimStart() method of the String class in JavaScript removes whitespace from the beginning of a string. It is an alias for trimLeft().


Syntax of String.trimStart()

There are 2 variations for the syntax of String.trimStart() method. They are:

1.
trimStart()

This method removes whitespace from the beginning of the string.

Returns value of type String.

2.
trimLeft()

This method alias for trimStart(). Removes whitespace from the beginning of the string.

Returns value of type String.



✐ Examples

1 Using trimStart() method

In JavaScript, the trimStart() method removes whitespace from the beginning of a string.

For example,

  1. We define a string variable str with the value ' Hello World' which has leading whitespace.
  2. We use the trimStart() method to remove the leading whitespace.
  3. The result is stored in the variable newStr.
  4. We log newStr to the console using the console.log() method.

JavaScript Program

const str = '   Hello World';
const newStr = str.trimStart();
console.log(newStr);

Output

Hello World

2 Using trimLeft() method

In JavaScript, the trimLeft() method, an alias for trimStart(), removes whitespace from the beginning of a string.

For example,

  1. We define a string variable str with the value ' Hello World' which has leading whitespace.
  2. We use the trimLeft() method to remove the leading whitespace.
  3. The result is stored in the variable newStr.
  4. We log newStr to the console using the console.log() method.

JavaScript Program

const str = '   Hello World';
const newStr = str.trimLeft();
console.log(newStr);

Output

Hello World

3 Comparing trimStart() and trimLeft() methods

In JavaScript, both trimStart() and trimLeft() methods perform the same function of removing whitespace from the beginning of a string.

For example,

  1. We define a string variable str with the value ' Hello World' which has leading whitespace.
  2. We use the trimStart() method to remove the leading whitespace and store the result in newStr1.
  3. We use the trimLeft() method to remove the leading whitespace and store the result in newStr2.
  4. We log newStr1 and newStr2 to the console using the console.log() method.

JavaScript Program

const str = '   Hello World';
const newStr1 = str.trimStart();
const newStr2 = str.trimLeft();
console.log(newStr1); // Hello World
console.log(newStr2); // Hello World

Output

Hello World
Hello World

Summary

In this JavaScript tutorial, we learned about trimStart() method of String: the syntax and few working examples with output and detailed explanation for each example.