Open In App

What is the use of the String.trim() Method in JavaScript ?

The String.trim() method in JavaScript is used to remove whitespace (spaces, tabs, and newline characters) from both ends of a string. It returns a new string with the leading and trailing whitespace removed.

Example: Here, the original string has extra spaces at the beginning and end. The trim() method is called on that string, resulting in a new string without the leading and trailing spaces.




const stringWithWhitespace = '   Hello, World!   ';
 
const trimmedString = stringWithWhitespace.trim();
 
console.log(trimmedString); // Output: 'Hello, World!'

Output
Hello, World!
Article Tags :