Search Qodo.co.uk

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!

// 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!

Post to Twitter

Post Details

Blog Archives

Blog Categories

Comments

5 Responses to “Javascript: trim leading and trailing spaces”

that’s nice…


  • Posted by Ace_NoOne
  • Permalink

Very nice – thanks!
(Why the s.replace(/\n /,"\n") though – what’s that for?)


That simply removes any spaces that come after a new line. It could be optimized to remove multiple spaces after a new line.


working very nice, thanx.


Implement the trim method as a prototype. Have a look at this article: http://www.whadiz.com/what-is.aspx/programming/javascript/javascript-trim


Leave Feedback

Your comments