Strip Whitespace From String

Whitespace, meaning tabs and spaces.

Vanilla JavaScript (Trim Leading and Trailing)

var str = " a b    c d e   f g   ";
var newStr = str.trim();
// "a b    c d e   f g"

That method is ES 5, so just in case you could polyfill it (IE 8 and down):

if (!String.prototype.trim) {
  String.prototype.trim = function () {
    return this.replace(/^\s+|\s+$/g, '');

jQuery (Trim Leading and Trailing)

If you're using jQuery anyway:

var str = " a b    c d e f g ";
var newStr = $.trim(str);
// "a b    c d e f g"

Vanilla JavaScript RegEx (Trim Leading and Trailing)

var str = "   a b    c d e f g ";
var newStr = str.replace(/(^\s+|\s+$)/g,'');
// "a b    c d e f g"

Vanilla JavaScript RegEx (Trim ALL Whitespace)

var str = " a b    c d e   f g   ";
var newStr = str.replace(/\s+/g, '');
// "abcdefg"


See the Pen Remove Whitespace from Strings by Chris Coyier (@chriscoyier) on CodePen.

Note that none of this works with other types of whitespace, for instance   (thin space) or   (non-breaking space).

You can also trim strings from the front or back.


  1. User Avatar
    Permalink to comment#

    You don’t need that “+” in the last case: “g” modifier takes care of that.

  2. User Avatar

    I think the results for first and second case are incorrect. In both cases newStr === "a b c d e f g", not "a b c d e f g".

    • User Avatar

      Hmm. It seems that the code formatter in CSS-Tricks actually removes extra white space between chars (lol), and I’m guessing that’s the reason the lines 5 and 11 are incorrect.

  3. User Avatar

    You can use replace to remove all extra spaces.
    ”.replace(/[ ]{2,}/g, ‘ ‘);
    e.g. ‘a s dsdsd f s d f s d dsfg’.replace(/[ ]{2,}/g, ‘ ‘); // “a s dsdsd f s d f s d dsfg”

  4. User Avatar
    Permalink to comment#

    How to remove the white space for buttons in the left side.

Leave a Comment

Posting Code!

You may write comments in Markdown. This makes code easy to post, as you can write inline code like `<div>this</div>` or multiline blocks of code in triple backtick fences (```) with double new lines before and after.

Code of Conduct

Absolutely anyone is welcome to submit a comment here. But not all comments will be posted. Think of it like writing a letter to the editor. All submitted comments will be read, but not all published. Published comments will be on-topic, helpful, and further the discussion or debate.

Want to tell us something privately?

Feel free to use our contact form. That's a great place to let us know about typos or anything off-topic.