Javascript- how to replace all spaces with dashes

code image

In this very short article, we will learn how to replace spaces with dashes using the .replace method in JS.

const str = "There is no place like 127.0.0.1."
const dashedStr = str.replace(/\s+/g, '-')

And that is all! Very simple regex

In case you want to create URL paths then you may want to consider also using .toLowerCase()

const str = "There is no place like 127.0.0.1."
const dashedStr = str.replace(/\s+/g, '-').toLowerCase()

And that is all! God speed!

Leave a Comment

Your email address will not be published. Required fields are marked *