How to trim() white spaces from a string?

The shortest form for jQuery:

string = $.trim(string);

Link


according to this page the best all-around approach is

return str.replace(/^\s\s*/, '').replace(/\s\s*$/, '');

Of course if you are using jQuery , it will provide you with an optimized trim method.


I know this question is ancient but now, Javascript actually does have a native .trim()

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/Trim


Well, as a lot of people always says, the trim function works pretty well, but if you don't want to use a whole framework just to perform a trim, it may be useful to take a look at its implementation. So here it is:

function( text ) { return (text || "").replace( /^(\s|\u00A0)+|(\s|\u00A0)+$/g, "" );}

The main advantages I see in this implementation, comparing to other solution already proposed here are:

  • The 'g' flag that allows you to perfom a trim on a multi-line string
  • The (text || "") syntax that ensure that the function will always work, even if the argument passed is null or undefined.

As a couple of others have already noted, it's usually best to do this sort of thing by using a third-party JS library. Not that trim() is a complicated function to build yourself, but there are so many functions that aren't native to JavaScript that you might need and end-up writing yourself, it soon becomes more cost-effective to use a library.

Of course, another advantage of using a JS library is that the authors do the hard work of ensuring that the functions work across all the major browsers, so that you can code to a standard interface and forget about the irritating differences between Internet Explorer and all the other browsers.