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 str, you can use this code:

str = str.replace(/^\s+|\s+$/g,'')
This code example uses the regular expression /^\s+|\s+$/g  which matches one or more occurrences of whitespace (\s) in the beginning and at the end of string. The g (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 string.replace() 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 string.trim() method, which allows you to rewrite the above much shorter:

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

Copyright © 1999-2011, JavaScripter.net.