Skip to content

How to replace white space inside a string in JavaScript

New Course Coming Soon:

Get Really Good at Git

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

How to replace white space inside a string in JavaScript

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, '')
Are you intimidated by Git? Can’t figure out merge vs rebase? Are you afraid of screwing up something any time you have to do something in Git? Do you rely on ChatGPT or random people’s answer on StackOverflow to fix your problems? Your coworkers are tired of explaining Git to you all the time? Git is something we all need to use, but few of us really master it. I created this course to improve your Git (and GitHub) knowledge at a radical level. A course that helps you feel less frustrated with Git. Launching May 21, 2024. Join the waiting list!
→ Get my JavaScript Beginner's Handbook
→ Read my JavaScript Tutorials on The Valley of Code
→ Read my TypeScript Tutorial on The Valley of Code

Here is how can I help you: