JavaScript Basics

JavaScript Advanced

JavaScript Arrays

JavaScript Functions

JavaScript Objects

JavaScript DOM

JavaScript String

How to remove whitespaces from the beginning of a string in JavaScript?

JavaScript provides two methods to remove whitespaces from the beginning of a string:

  1. String.prototype.trimLeft()
  2. String.prototype.trimStart()

In this tutorial, you will learn how to use the trimLeft() method.

The syntax for the trimLeft() method is:

let leftTrimmedString = originalString.trimLeft();

Note: The trimLeft() method does not modify the original string and returns a left-trimmed string.

Also, in JavaScript following characters are considered whitespaces:

  • Spaces
  • Tabs
  • Newline
  • Carriage return
  • Form feed

The following example removes the whitespaces from the left of a string.

let str = "   JavaScript String     ";
let leftTrimmedString = str.trimLeft();

console.log('Left-trimmed String');
console.log(leftTrimmedString);
console.log('Original String');
console.log(str);

Output

Left-trimmed String
"JavaScript String     "
Original String
"   JavaScript String     "

Recommended Posts