What is the trim() method in JavaScript?

The trim() method in JavaScript removes the whitespace from both ends of a string without changing the original string. The functionality of trim method is shown in the illustration given below:

Syntax

The trim() method is declared as follows:

Parameters

The trim method does not take any parameters.

Return value

The trim method returns a string with whitespace removed from both ends of the string.

Example

The example below shows the use of trim method in JavaScript:

var str = " Hello! ";
//Call trim() method
console.log(str.trim());
var str2 = "How are you ? ";
//Call trim() method
console.log(str2.trim());

Free Resources

Copyright ©2026 Educative, Inc. All rights reserved