string.replace() function. Removing all whitespace can be cumbersome when it comes to tabs and line breaks.
string.replace() method supports regular expressions. This tutorial shows you how to remove all whitespace from a string value.
Node.js Series Overview
- Callback and Promise Support in your Node.js Modules
- Increase the Memory Limit for Your Process
- Why You Should Add “node” in Your Travis Config
- Create a PDF from HTML with Puppeteer and Handlebars
- Create Your Own Custom Error
- Extend Multiple Classes (Multi Inheritance)
- Get a File’s Created Date
- Get a File’s Last Modified/Updated Date
- Human-Readable JSON.stringify() With Spaces and Line Breaks
- Write a JSON Object to a File
- How to Create an Empty File
- Run Async Functions/Promises in Sequence
- Run Async Functions/Promises in Parallel
- Run Async Functions in Batches
- How to Merge Objects (Coming soon)
Remove all Whitespace From a String
string.replace() method supports regular expressions (Regex) to find matches within the string. There’s a dedicated Regex to match any whitespace character:
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
gat the end indicates iterative searching throughout the full string
That’s it! Enjoy coding & make it rock!