JavaScript String trimEnd() Method



The JavaScript String trimEnd() method is used to remove whitespace characters from the end (right side) of the current string. It returns a new string without modifying the original string. If the end of the string has no whitespace, the new string will be the same as the original string.

To remove whitespace characters from both ends of a string, we can use the trim() method. To remove whitespace characters from only one end of a string, you can use the trimStart() or trimEnd() methods, depending on which end you want to trim.

Syntax

Following is the syntax of JavaScript String trimEnd() method −

trimEnd()

Parameters

  • It does not accept any parameters.

Return value

This method returns a new string with whitespace characters removed from the end (right side) of the current string.

Example 1

If the end (right side) of the current string "Tutorials Point" has no whitespace characters, this method returns the original string unchanged.

<html>
<head>
<title>JavaScript String trimEnd() Method</title>
</head>
<body>
<script>
   const str = "Tutorials Point";
   document.write("Original string: ", str);
   document.write("<br>New string: ", str.trimEnd());
</script>    
</body>
</html>

Output

The above program returns "Tutorials Point".

Original string: Tutorials Point
New string: Tutorials Point

Example 2

In this example, we use the JavaScript String trimEnd() method to trim the white spaces from the end of the string " Hello World! ".

<html>
<head>
<title>JavaScript String trimEnd() Method</title>
</head>
<body>
<script>
   const str = " Hello World! ";
   document.write("Original string: ", str);
   document.write("<br>Length of original string: ", str.length);
   document.write("<br>New string: ", str.trimEnd());
   document.write("<br>Length of new string: ", str.trimEnd().length);
</script>    
</body>
</html>

Output

After executing the above program, it trimmed the white spaces from both ends and returned a new string "Hello World!".

Original string: Hello World!
Length of original string: 14
New string: Hello World!
Length of new string: 13
Advertisements