Javascript - String trim() Method

The trim() method removes whitespace from both sides of a string.

Description

The trim() method removes whitespace from both sides of a string.

The trim() method does not change the original string.

Syntax

string.trim()

Parameters

None

Return

A String, representing the string with removed whitespace from both ends

Example

Remove whitespace from both sides of a string:

Demo

//alert the string with removed whitespace.
var str = "       Hello World!       ";
console.log(">"+str.trim()+"<");

//you can remove whitespaces from both sides of a string with a regular expression:
function myTrim(x) {
    return x.replace(/^\s+|\s+$/gm,'');
}
var str = myTrim("        Hello World!        ");
console.log(">"+str+"<");

Result