How to Replace White Space in Strings using Regex in JavaScript

Regular expressions are a powerful way to work with and manipulate strings.
One of the most common operations you will perform on strings is to replace whitespace with another character, usually nothing (removing whitespace).
In this post, we'll learn how we can use regex to replace whitespace in a string in JavaScript.
How to Replace Whitespace in a String in JavaScript
To replace whitespace in a string in JavaScript, you can use the replace()
method.
This method returns a new string with some or all matches of a pattern replaced by a replacement.
First let's define a long sentence:
const sentence = "The quick brown fox jumps over the lazy dog.";
console.log(sentence);
The quick brown fox jumps over the lazy dog.
Now let's remove all the white space in this sentence by replacing all the white space with nothing:
const sentence = "The quick brown fox jumps over the lazy dog.";
sentence.replace(/\s/g, "");
console.log(sentence);
Thequickbrownfoxjumpsoverthelazydog.
The reason why this work is that we are using a regular expression to match all the white space in the string.
The regular expression we used is /\\s/g
which matches all the white space in the string.
The global flag g
is used to replace all the white space in the string, instead of just the first match.
Finally, we are replacing the white space with a blank string, which is why the string is now all one word.
If we wanted to replace the white space with a dash, we could do this:
const sentence = "The quick brown fox jumps over the lazy dog.";
sentence.replace(/\s/g, "-");
console.log(sentence);
The-quick-brown-fox-jumps-over-the-lazy-dog.
How to Count how many Whitespace Characters are in a String in JavaScript
To count how many whitespace characters are in a string in JavaScript, you can use the match()
method.
We can use the same regular expression we used to replace the white space to count how many white space characters are in the string.
First let's define a long sentence:
const sentence = "The quick brown fox jumps over the lazy dog.";
console.log(sentence);
The quick brown fox jumps over the lazy dog.
Now let's count how many white space characters are in this sentence:
const sentence = "The quick brown fox jumps over the lazy dog.";
const length = sentence.match(/\s/g).length;
console.log(length);
8
Conclusion
In this post, we learned how to replace whitespace in a string in JavaScript.
Simply use the replace()
method and pass in a regular expression to match all the white space in the string, and then replace it with another character.
We also learned how to count how many whitespace characters are in a string in JavaScript by using the match()
method.
Thanks for reading!
If you want to learn about web development, founding a start-up, bootstrapping a SaaS, and more, follow me on Twitter! You can also join the conversation over at our official Discord!
Leave us a message!