Trim String With Regular Expressions
Using regular expressions, we can shorten the trim string JavaScript function quite a bit. First, leading and trailing spaces are removed from the string in a couple of statements. Build a regular expression statement that will find one or more starting white space characters (space, tab, form feed, or line feed), then any character (\W\w ends up being anything), then one or more ending white spaces after a word boundary. If that pattern is found in the input string, maintain only the middle characters (the \W\w part).
To trim interior consecutive spaces, set up the regular expression object to hold two spaces (var obj = / /g; has 2 spaces). While 2 spaces is somewhere in the string, replace all consecutive spaces with a single space. This only does one pass through, so if there were 3 consecutive spaces, it would replace the first 2 with a single space and end up with 2 spaces still. So the while loop is necessary.
function trim(value) {
var temp = value;
var obj = /^(\s*)([\W\w]*)(\b\s*$)/;
if (obj.test(temp)) { temp = temp.replace(obj, '$2'); }
var obj = / /g;
while (temp.match(obj)) { temp = temp.replace(obj, " "); }
return temp;
}
Note that if you only want to trim the leading and trailing spaces (and not get rid of interior consecutive spaces), you can get rid of the second instance where "obj" is set, and the while loop.
Another way to accomplish the replacing of interior multiple spaces is to replace all instances of one or more spaces with a single space. So if there already is one space, it will be replaced with one space. But if there are 2 or more consecutive spaces, all will be replaced with 1 space. This eliminates the while loop. However, if the string is just a line of spaces, then this results in a single space, so an additional check needs to be made. Using this method, the function becomes:
function trim(value) {
var temp = value;
var obj = /^(\s*)([\W\w]*)(\b\s*$)/;
if (obj.test(temp)) { temp = temp.replace(obj, '$2'); }
var obj = / +/g;
temp = temp.replace(obj, " ");
if (temp == " ") { temp = ""; }
return temp;
}