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.
1 comment:
Great thinking, and excellent explanation.
Post a Comment