HOME HTML CSS JAVASCRIPT SQL PHP JQUERY XML ASP.NET MORE...
REFERENCES | EXAMPLES | FORUM | ABOUT

JavaScript String trim() Method

String Object Reference JavaScript String Object

Example

Remove whitespace from both sides of a string:

var str = "       Hello World!        ";
alert(str.trim());

The alert box will display:

Hello World!

Try it yourself »

Definition and Usage

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

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


Browser Support

Internet Explorer Firefox Opera Google Chrome Safari

The trim() method is supported in all major browsers.

Note: The trim() method is not supported in Internet Explorer 8 and earlier versions.


Syntax

string.trim()

Parameters

None.

Return Value

Type Description
String The string with removed whitespace

Technical Details

JavaScript Version: 1.8


More Examples

Example

For browsers that do not support this method, you can remove whitespaces from both sides of a string with a regular expression:

function myTrim(x)
{
return x.replace(/^\s+|\s+$/gm,'');
}

function myFunction()
{
var str = myTrim("        Hello World!        ");
alert(str);
}

Try it yourself »


String Object Reference JavaScript String Object

Your suggestion:

Close [X]

Thank You For Helping Us!

Your message has been sent to W3Schools.

Close [X]
Search w3schools.com:

WEB BUILDING

Download XML Editor FREE Website BUILDER Free HTML5 Templates

SHARE THIS PAGE