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!

The trim function

The function makes 3 regular expression calls to remove spaces at the start, the end and any multiple spaces.

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

Comments 10

  1. Try using it like this:

    mystring = " I want to remove spaces ";
    mystring = trim(mystring);
    // mystring now is: I want to remove spaces

  2. i just want to remove first and last and extra spaces in a string

    function trim(str){

    please help dhanabati
  3. Very nice - thanks! (Why the s.replace(/\n /,"\n") though - what's that for?) Ace_NoOne
  4. That simply removes any spaces that come after a new line. It could be optimized to remove multiple spaces after a new line. Stewart
  5. working very nice, thanx. Rishi Katara
  6. Implement the trim method as a prototype. Have a look at this article: Ryan
  7. Thanks, I was trying hard to make it work, found regexp to be kinda confusing, your method is great. Hector
  8. Can u pls explain me the code.. am a newbie to javascript.. SanthanaKrishnan N
  9. Thanks a lot for the code. It is very helpful for people like me:) Mads
  10. Great Stuff !!!!!!! Sascha
  1. 1

Got something to say?

Join the discussion! You know how these things work; enter your details and comments below and be heard.

  1. Allowed tags: <b><i><br>