image: Jeff Couturier

Jeff Couturier
designer / developer

Trim Spaces From a String With JavaScript

written by Jeff on 2008-09-22

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) {
  return theString.replace(/^\s+|\s+$/g, '');
}

And that’s it. Quick and easy.