JavaScript String trimEnd()
Syntax & Examples
String.trimEnd() method
The trimEnd() method of the String class in JavaScript removes whitespace from the end of a string. It is an alias for trimRight().
Syntax of String.trimEnd()
There are 2 variations for the syntax of String.trimEnd() method. They are:
trimEnd()
This method removes whitespace from the end of the string.
Returns value of type String
.
trimRight()
This method alias for trimEnd(). Removes whitespace from the end of the string.
Returns value of type String
.
✐ Examples
1 Using trimEnd() method
In JavaScript, the trimEnd()
method removes whitespace from the end of a string.
For example,
- We define a string variable
str
with the value'Hello World '
which has trailing whitespace. - We use the
trimEnd()
method to remove the trailing 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.trimEnd();
console.log(newStr);
Output
Hello World
2 Using trimRight() method
In JavaScript, the trimRight()
method, an alias for trimEnd()
, removes whitespace from the end of a string.
For example,
- We define a string variable
str
with the value'Hello World '
which has trailing whitespace. - We use the
trimRight()
method to remove the trailing 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.trimRight();
console.log(newStr);
Output
Hello World
3 Comparing trimEnd() and trimRight() methods
In JavaScript, both trimEnd()
and trimRight()
methods perform the same function of removing whitespace from the end of a string.
For example,
- We define a string variable
str
with the value'Hello World '
which has trailing whitespace. - We use the
trimEnd()
method to remove the trailing whitespace and store the result innewStr1
. - We use the
trimRight()
method to remove the trailing 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.trimEnd();
const newStr2 = str.trimRight();
console.log(newStr1); // Hello World
console.log(newStr2); // Hello World
Output
Hello World Hello World
Summary
In this JavaScript tutorial, we learned about trimEnd() method of String: the syntax and few working examples with output and detailed explanation for each example.