DEV Community

San
San

Posted on

How to Replace Spaces with Dashes in a JavaScript String

Output 1

let myString = "Hello World";
let stringWithoutSpaces = myString.replace(/\s+/g, '-');

console.log(stringWithoutSpaces); // "Hello-World"
Enter fullscreen mode Exit fullscreen mode

Output 2

let myString = "  Hello World ";
let trimmedString = myString.trim();
let formattedString = trimmedString.replace(/\s+/g, '-');

console.log(formattedString); // "Hello-World"
Enter fullscreen mode Exit fullscreen mode

Top comments (1)

Collapse
 
jonrandy profile image
Jon Randy 🎖️

Your code is replacing more than just spaces, it will also replace carriage returns, tabs, and all other whitespace - potentially wrecking some formatting. Not sure if that is what you intended?