javascript
  1. javascript-trim

JavaScript trim()

The trim() method in JavaScript is used to remove whitespace characters from both ends of a string. The whitespace characters that are removed include spaces, tabs, and newlines. The method returns the modified string without changing the original string.

Syntax

str.trim()

Example

const str = "   Hello, World!   ";
console.log(str.trim()); // Output: "Hello, World!"

Output

"Hello, World!"

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>JavaScript Output</title>
</head>
<body>

<!-- Your JavaScript code goes here -->
<script>
  const str = "   Hello, World!   ";
  const trimmedStr = str.trim();
  document.write('<p>' + trimmedStr + '</p>');
</script>

</body>
</html>

Try Playground

Explanation

The trim() method removes the whitespace characters from both ends of the string " Hello, World! " and returns the new string "Hello, World!".

Use

The trim() method is useful when dealing with user input, where they may accidentally add extra spaces at the beginning or end of their input. It can also be used to remove unwanted whitespace characters from the beginning or end of a string that is retrieved from a data source.

Important Points

  • The trim() method doesn't modify the original string, it only returns a new modified string.
  • The trim() method removes only leading and trailing whitespace characters, not any whitespace characters in between the string.
  • The trim() method is not supported in Internet Explorer 8 and earlier versions.

Summary

The trim() method in JavaScript is a useful string method to remove whitespace characters from both ends of a string. It helps to simplify string manipulation tasks and improve the quality of user input.

Published on: