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

Example

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

The trim() method is not supported in Internet Explorer 8 or lower.

If you need to support IE 8, you can use replace() with a regular expression instead:

Example

var str = "       Hello World!        ";
alert(str.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, ''));
 

You can also use the replace solution above to add a trim function to the JavaScript String.prototype:

Example

if (!String.prototype.trim) {
  String.prototype.trim = function () {
    return this.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, '');
  };
}
var str = "       Hello World!        ";
alert(str.trim());



Practice Excercise Practice now