How to replace spaces in a string in JavaScript

Learn how to use regular expressions to replace all whitespace in a string using JavaScript

It is a very common requirement to replace all whitespace in a string.

For example, the last time I used this method in the API endpoint that received the image. I use the original image name to store it, but if it contains a space, it will break my function (or other special characters, but we will focus on the space)

Therefore, I researched the best way to accomplish what I wanted to do. It turned out that oneRegular expressionThis is what I need!

this is all

const name = 'Hi my name is Flavio'
name.replace(/\s/g, '') //HimynameisFlavio

How to replace white space inside a string in JavaScript

This\sThe meta characters in JavaScript regular expressions match any whitespace characters: spaces, tabs, newlines, and Unicode spaces. withgThe flag tells JavaScript to replace it multiple times. If you miss it, it will only replace the first occurrence of the blank.

please remembernameThe value does not change. Therefore, if needed, you need to assign it to a new variable:

const name = 'Hi my name is Flavio'
const nameCleaned = name.replace(/\s/g, '')

Download mine for freeJavaScript beginner's manual


More js tutorials: