Open In App

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

Last Updated : 30 Jan, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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.

Javascript




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


Output

Hello, World!

Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads