DEV Community

Cover image for Vanilla JavaScript Replace All Whitespaces
Chris Bongers
Chris Bongers

Posted on • Originally published at daily-dev-tips.com

4 1

Vanilla JavaScript Replace All Whitespaces

Today we'll be looking 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:

var string = "You've got a friend in me.";
Enter fullscreen mode Exit fullscreen mode

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

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

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

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

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.

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

Image of Stellar post

How a Hackathon Win Led to My Startup Getting Funded

In this episode, you'll see:

  • The hackathon wins that sparked the journey.
  • The moment José and Joseph decided to go all-in.
  • Building a working prototype on Stellar.
  • Using the PassKeys feature of Soroban.
  • Getting funded via the Stellar Community Fund.

Watch the video

Top comments (0)

Jetbrains image

Build Secure, Ship Fast

Discover best practices to secure CI/CD without slowing down your pipeline.

Read more

👋 Kindness is contagious

Explore this insightful post in the vibrant DEV Community. Developers from all walks of life are invited to contribute and elevate our shared know-how.

A simple "thank you" could lift spirits—leave your kudos in the comments!

On DEV, passing on wisdom paves our way and unites us. Enjoyed this piece? A brief note of thanks to the writer goes a long way.

Okay