How to Replace White Space inside Strings with JavaScript (using RegEx)

Learn how to replace white space inside strings with JavaScript by using Regex (Regular Expressions) — a tool for finding patterns within text.

Regex (often spelled “RegEx or “RegExp”) is a performant tool for working with strings (text). Regex most common use cases are:

  • Text validation
  • Text searching

Today you’ll learn from a simple example that uses regex to replace all the white space in a line of text (string) with nothing — but you could use the following code example to replace white space with other characters.

White space is considered a character. So every space between words in this sentence you’re reading now is counted as one white space character.

This sentence has 6 white space characters.

To replace white space characters, regex has a so-called meta-character called \s that looks for a single white space character, including newline, tabs, and Unicode.

Like this:

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

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

What’s happening in the code:

  • First, we attach the replace() method to the sentence variable that references the string that we want to remove white space from.
  • Then add the aforementioned \s meta character as an argument to find white space characters. Because backslash (\) is a reserved escape character in JavaScript, we add / in front of it to unescape it, so it becomes /\s/.
  • Then we use the global g flag, which tells JavaScript that we want to find all the white space characters from the string. If you don’t add the g, only the first white space instance (between This sentence) will be replaced.
  • Finally, what are we replacing the white space with what? Any empty string "" which is what removes the white space characters and makes every word glued into a single word.

Note: we haven’t modified the original sentence variable by doing this, we’re just using console.log() to print out how it would look if you use the replace(/\s/g, "") regex method on it.

If you want to change the value of the sentence variable to contain no white spaces, you need to assign it to a new variable, and then reference that variable from now on when you need access to it.

Like this:

const sentence = "This sentence has 6 white space characters."
const sentenceRemoveWhiteSpace = sentence.replace(/\s/g, "")

console.log(sentenceRemoveWhiteSpace)
// Thissentencehas6whitespacecharacters.

And just to make sure that my math is right, let’s use another useful regex method called match() to count the number of white space characters in the original sentence variable and see if it’s indeed 6:

console.log(sentence.match(/\s/g).length)
// 6

Phew, it is!


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