Javascript: trim leading and trailing spaces
Here's a quick function to remove leading, trailing and multiple spaces from a string using regular expression which is much faster that using loops! This can be used to tidy up input values.
The trim function
The function makes 3 regular expression calls to remove spaces at the start, the end and any multiple spaces.
// remove multiple, leading or trailing spaces
function trim(s) {
s = s.replace(/(^\s*)|(\s*$)/gi,"");
s = s.replace(/[ ]{2,}/gi," ");
s = s.replace(/\n /,"\n");
return s;
}
To use it, do something like this:-
alert(trim(" My name is stewart "));
It will strip the spaces at the start, end and also any multiple spaces in the middle to give a nicely formatted string! Simple, eh?
Download the complete Javascript remove leading and trailing spaces now!
Like this?
Archives
Categories
Comments (6)
What others have said about this post.
-
vectorialpx said:
-
Ace_NoOne said:
-
Stewart said:
-
Rishi Katara said:
-
Ryan said:
Last Edit: February 12, 2010, 23:19:10 by qodo -
Hector said:

