How to Remove All Spaces in a String with JavaScript

To remove all spaces in a string with JavaScript, you can use RegEx:

const sentence = "This sentence has 6 white space characters."

console.log(sentence.replace(/\s/g, ""))
// "Thissentencehas6whitespacecharacters."

The example above only logs out the result, it doesn’t save the changes.

If you want to permanently remove the white space from your text, you have to create a new variable and assign the value of sentence.replace(/\s/g, ""):

// Sentence with whitespaces
const sentence = "This sentence has 6 white space characters."

// Sentence without whitespace
const sentenceRemoveWhiteSpace = sentence.replace(/\s/g, "")

console.log(sentenceRemoveWhiteSpace)
// Thissentencehas6whitespacecharacters.

Has this been helpful to you?

You can support my work by sharing this article with others, or perhaps buy me a cup of coffee 😊

Kofi

Share & Discuss on