Snippets: trim spaces from a string with Javascript
I see this question all the time, so here’s a quick reference for trimming spaces from strings using Javascript.
var newString = oldString.replace(/^\s+|\s+$/g, '');
I’d highly suggest making this a re-usable function. It’ll save you all kinds of time and can easily be included in a common functions script on all of your sites.
function trimString(theString) {
newString = theString.replace(/^\s+|\s+$/g, '');
return newString;
}
And that’s it. Quick and easy.


Thanks for this handy piece of code!
why not just make it inline instead of creating a new string var?
function trimString(theString) {
return theString.replace(/^\s+|\s+$/g, '');
}
@Clint Rutkas:
No particular reason. The new string var is just a carry-over from the single-line command before being wrapped in a function.