Subscribe

Vanilla JavaScript Replace All Whitespaces

โœ๏ธ

How can we replace or remove all whitespaces in a string?

12 Aug, 2020 ยท 1 min read

Today we'll look into a widespread use case; we want to replace all whitespace occurrences from a string. Think about an input we want to save as a URL, and we need to replace the whitespaces with dashes. Or an image where we need to remove them.

JavaScript Replace All Whitespace

To remove all whitespaces, we have multiple options, but the best one is to use a regular expression.

Let's say we have the following string:

const string = "You've got a friend in me.";

And let's first start by just removing the whitespaces:

console.log(string.replace(/\s/g, ''));
// You'vegotafriendinme.

Now let's try and replace them all for dashes:

console.log(string.replace(/\s/g, '-'));
// You've-got-a-friend-in-me.

Awesome!

So how does this regular expression work?

\s means any whitespace character, and g means it's a global modifier and must match any search occurrences!

You can have a play with this on Codepen.

See the Pen Vanilla JavaScript Replace All Whitespaces by Chris Bongers (@rebelchris) on CodePen.

Thank you for reading, and let's connect!

Thank you for reading my blog. Feel free to subscribe to my email newsletter and connect on Facebook or Twitter

Spread the knowledge with fellow developers on Twitter
Tweet this tip
Powered by Webmentions - Learn more

Read next ๐Ÿ“–

JavaScript sending data between windows

9 Sep, 2022 ยท 4 min read

JavaScript sending data between windows

Using the native payment request JavaScript API

9 Aug, 2022 ยท 8 min read

Using the native payment request JavaScript API

Join 1829 devs and subscribe to my newsletter