How to replace space with hyphen (dash) in JavaScript

How to replace space with hyphen (dash) in JavaScript

Posted by Raquel Crist on July 19, 2022

How to replace space with hyphen (dash) in JavaScript

How to replace space with hyphen (dash) in JavaScript

Posted by Raquel Crist on July 19, 2022

Here is how you can convert space to hyphen on a string in JavaScript. The toLowerCase() method will also be added to make all the characters lower case, in case you want the string to be a slug or as part of a url.

Using the replaceAll() method:

let str = "new page Link";

let value = str.replaceAll(" ", "-").toLowerCase();
console.log(value); // new-page-link

Using Regex 

let str = "new page Link";

let value = str.replace(/\s+/g, "-").toLowerCase();
console.log(value); // new-page-link

Using the join() method:

let str = "new page Link";

let value = str.split(" ").join("-").toLowerCase();
console.log(value); // new-page-link

 

Any question?
This field is required
Your question have been successfully submitted and will be reviewed before published
Please login to ask a question