Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

JavaScript trim() Method

JavaScript trim() Method

String Object Reference JavaScript String object

Example

Removes whitespace from both ends of a string:

var

str

=

"

Runoob

"

;

alert

(

str

.

trim

(

)

)

;

Output result:

Runoob

Try it »


Definition and Usage

The trim() method removes whitespace from both ends of a string, including spaces, tab characters, newlines, and other whitespace characters.

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

The trim() method does not apply to null, undefined, or Number types.


Browser support

The numbers in the table indicate the first browser version that supports this property.

Method
trim() 10.0 9.0 3.5 5.0 10.5

Syntax



string.trim()

Parameter value

none.

Return Value

Type Description
String

Returns the string with leading and trailing whitespace removed.

Technical Details

JavaScript version: ECMAScript 5

More examples

Example

If your browser does not support the trim() method, you can use a regular expression instead:

function

myTrim

(

x

)

{

return

x

.

replace

(

/^\

s

+|\

s

+$/

gm

,

'

'

)

;

}

function

myFunction

(

)

{

var

str

=

myTrim

(

"

Runoob

"

)

;

alert

(

str

)

;

}

Output result:

Runoob

Try it »


String Object Reference JavaScript String object