Open In App

JavaScript String trim() Method

Last Updated : 14 Mar, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

The JavaScript trim() method removes whitespace from both ends of a string and returns the trimmed string. The whitespace includes spaces, tabs, and newlines.

This method does not modify the original string, it returns a new trimmed string.

Syntax:

str.trim();

Parameters:

This method does not accept any parameter.

Return value:

Returns a new string, without any of the leading or trailing white spaces. 

JavaScript String trim() Method Examples

Example 1: Trimming Whitespace from a String

A string containing extra whitespace at the end is trimmed using the trim() method. The original string “GeeksforGeeks ” becomes “GeeksforGeeks”.

JavaScript
function func() {
    let str = "GeeksforGeeks     ";
    let st = str.trim();
    console.log(st);
}
func();

Output
GeeksforGeeks

Example 2: Trimming Leading Whitespace from a String

The trim() method is used to remove leading whitespace from the original string ” GeeksforGeeks”, resulting in the trimmed string “GeeksforGeeks”.g and trailing spaces in the string str.

JavaScript
function func() {

    // Original string containing whitespace
    let str = "   GeeksforGeeks";

    // Trimmed string
    let st = str.trim();
    console.log(st);
}
func();

Output
GeeksforGeeks

We have a complete list of Javascript string methods, to check those please go through this Javascript String Complete reference article.

Supported Browser:


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads