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:
trimStart()
This method removes whitespace from the beginning of the string.
Returns value of type String
.
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,
- We define a string variable
str
with the value' Hello World'
which has leading whitespace. - We use the
trimStart()
method to remove the leading whitespace. - The result is stored in the variable
newStr
. - We log
newStr
to the console using theconsole.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,
- We define a string variable
str
with the value' Hello World'
which has leading whitespace. - We use the
trimLeft()
method to remove the leading whitespace. - The result is stored in the variable
newStr
. - We log
newStr
to the console using theconsole.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,
- We define a string variable
str
with the value' Hello World'
which has leading whitespace. - We use the
trimStart()
method to remove the leading whitespace and store the result innewStr1
. - We use the
trimLeft()
method to remove the leading whitespace and store the result innewStr2
. - We log
newStr1
andnewStr2
to the console using theconsole.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.