Grow your CSS skills. Land your dream job.

Last updated on:

Strip Whitespace From String

Whitespace, meaning tabs and spaces.

// Remove leading and trailing whitespace
// Requires jQuery
var str = " a b    c d e f g ";
var newStr = $.trim(str);
// "a b c d e f g"

// Remove leading and trailing whitespace
// JavaScript RegEx
var str = "   a b    c d e f g ";
var newStr = str.replace(/(^\s+|\s+$)/g,'');
// "a b c d e f g"

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

Doesn't work with other types of whitespace though, for instance   (thin space) or   (non-breaking space)

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

  • Use Markdown, and it will escape the code for you, like `<div class="cool">`.
  • Use triple-backticks for blocks of code.
    ``` 
    <div>
      <h1>multi-line block of code</h1>
      <span>be cool yo.</span>
    </div>
    ```
  • Otherwise, escape your code, like <code>&lt;div class="cool"&gt;</code>. Markdown is just easier though.

Current ye@r *

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