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
- 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
- Write a JSON Object to a File
- How to Create an Empty File
- How to Merge Objects
- Retrieve a Request’s IP Address in Node.js
- Detect the Node.js Version in a Running Process or App
- String Replace All Appearances
- How to Run an Asynchronous Function in Array.map()
- How to Reset and Empty an Array
- for…of vs. for…in Loops
- Get an Array With Unique Values (Delete Duplicates)
- Callback and Promise Support in your Node.js Modules
- Run Async Functions/Promises in Sequence
- Run Async Functions/Promises in Parallel
- Run Async Functions in Batches
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!