Grow your CSS skills. Land your dream job.

Last updated on:

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"

Demos

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.

Comments

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

  2. 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".

    • Rubinous

      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.

Leave a Comment

Posting Code

Markdown is supported in the comment area, so you can write inline code in backticks like `this` or multiline blocks of code in in triple backtick fences like this:

```
<div>Example code</div>
```

You don't need to escape code in backticks, Markdown does that for you. If anything screws up, contact us and we can fix it up for you.

*May or may not contain any actual "CSS" or "Tricks".