Remove All Whitespace From a String in JavaScript

String replacements in JavaScript are a common task. It still can be tricky to replace all appearances using the string.replace() function. Removing all whitespace can be cumbersome when it comes to tabs and line breaks.

Luckily, JavaScript’s string.replace() method supports regular expressions. This tutorial shows you how to remove all whitespace from a string value.

Node.js Series Overview

  1. Get Number of Seconds Since Epoch in JavaScript
  2. Get Tomorrow’s Date in JavaScript (Coming soon)
  3. Increase a Date in JavaScript by One Week (Coming soon)

Remove all Whitespace From a String

JavaScript’s string.replace() method supports regular expressions (Regex) to find matches within the string. There’s a dedicated Regex to match any whitespace character:\s.

Combine this Regex to match all whitespace appearances in the string to ultimately remove them:

const stripped = '    My String With A    Lot Whitespace  '.replace(/\s+/g, '')

// 'MyStringWithALotWhitespace'

Let’s look at the individual parts of the Regex and determine what they do:

  • \s: matches any whitespace symbol: spaces, tabs, and line breaks
  • +: match one ore more of the preceding tokens (referencing \s)
  • g: the g at the end indicates iterative searching throughout the full string

That’s it! Enjoy coding & make it rock!

Explore the Library

Find interesting tutorials and solutions for your problems.