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
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, '')
More js tutorials:
- The Object isPrototypeOf() method
- The Object entries() method