How to replace white space inside a string in JavaScript
Find out how to use a regex to replace all white space inside a string using JavaScript
Replacing all the white space inside a string is a very common need.
For example I last used this inside an API endpoint that received an image. I used the original image name to store it, but if it contained a space it was breaking my functionality (or other special chars, but let’s focus on spaces)
So I researched the best way to do what I wanted. Turns out, a regular expression was what I needed!
Here it is, in full
const name = 'Hi my name is Flavio'
name.replace(/\s/g, '') //HimynameisFlavio
The \s
meta character in JavaScript regular expressions matches any whitespace character: spaces, tabs, newlines and Unicode spaces. And the g
flag tells JavaScript to replace it multiple times. If you miss it, it will only replace the first occurrence of the white space.
Remember that the name
value does not change. So you need to assign it to a new variable, if needed:
const name = 'Hi my name is Flavio'
const nameCleaned = name.replace(/\s/g, '')
I wrote 17 books to help you become a better developer, download them all at $0 cost by joining my newsletter
- C Handbook
- Command Line Handbook
- CSS Handbook
- Express Handbook
- Git Cheat Sheet
- Go Handbook
- HTML Handbook
- JS Handbook
- Laravel Handbook
- Next.js Handbook
- Node.js Handbook
- PHP Handbook
- Python Handbook
- React Handbook
- SQL Handbook
- Svelte Handbook
- Swift Handbook
JOIN MY CODING BOOTCAMP, an amazing cohort course that will be a huge step up in your coding career - covering React, Next.js - next edition February 2025