Friday, February 19, 2010

JavaScript: trim leading or trailing spaces from a string


There is no built-in function to remove leading or trailing spaces from a string in JavaScript. To do that, we can use the replace() method of the String object.

The syntax of String's replace() method is:
string.replace(regexp/substr,newstring);
The first parameter can be a regular expression. The second parameter is a new string to replace what the regular expression matches in the string. So to trim the leading or trailing spaces, we can do this:
mystring = mystring.replace(/^\s+|\s+$/g, "");
The first parameter /^\s+|\s+$/g is a regular expression that matches the leading or trailing white-space characters. Let us break it down to see what it means:
  • \s matches a white-space character;
  • + matches the preceding element one or more times, so \s+ matches 1 or more white-space characters;
  • ^ matches the starting position of the string, so ^\s+ matches 1 or more leading white-space characters;
  • $ matches the ending position of the string, so \s+$ matches 1 or more trailing white-space characters;
  • | means or, so ^\s+|\s+$ matches 1 or more leading or trailing white-space characters;
  • /.../ means search;
  • g means global, so it will continue and search for the trailing white-space characters after it have found the leading white-space characters.
When a pattern is found in mystring, i.e. leading or trailing white-space characters are found, they will be replaced with an empty string "". The result? They are trimmed.

1 comment:

Anonymous said...

Great thinking, and excellent explanation.

 
Get This <