Trimming a string in JavaScript

JavaScript FAQ | JavaScript Strings and RegExp FAQ  

Question: How do I trim leading and trailing spaces of a string?

Answer: To remove all leading and trailing spaces from a string

, you can use this code:
str = str.replace(/^\s+|\s+$/g,'')
This code example uses the regular expression
which matches one or more occurrences of whitespace (
) in the beginning and at the end of string. The
(global) flag in the regular expression specifies that a global search should be performed (e.g. even if a match is found in the beginning of the string, the matching process must still continue and attempt to find whitespaces at the end of the string, too). The
method is used to replace all leading and trailing whitespace characters with an empty string.

Many modern browsers (such as Firefox 3, Opera 11, Safari 5.x, Chrome 10, Internet Explorer 9 in standards mode) support the

method, which allows you to rewrite the above much shorter:
str = str.trim()
For browsers that do not support
, e.g. Internet Explorer 8 or earlier, you can add your own
method to string object's
by including the following script in the
section of your page, prior to any script that uses
if (!String.prototype.trim) {
 String.prototype.trim = function() {
  return this.replace(/^\s+|\s+$/g,'');

Copyright © 1996-2018,