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.
Hi, you’ll need to prefix newString with a var statement within the trimString function. Currently “newString” is being created in the global (window) scope.
I too recommend returning the result of theString.replace instead of creating a single use variable.
Keep up the good stuff
Actually Matt, the var keyword is not required unless you’re concerned about variable name conflicts with newString within the global scope. If you’re using unique names for your variables, this isn’t an issue and the var keyword can be omitted.