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.
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
sentencevariable that references the string that we want to remove white space from.
- Then add the aforementioned
\smeta character as an argument to find white space characters. Because backslash (
/in front of it to unescape it, so it becomes
- Then we use the global
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.
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!