Output 1
let myString = "Hello World";
let stringWithoutSpaces = myString.replace(/\s+/g, '-');
console.log(stringWithoutSpaces); // "Hello-World"
Output 2
let myString = " Hello World ";
let trimmedString = myString.trim();
let formattedString = trimmedString.replace(/\s+/g, '-');
console.log(formattedString); // "Hello-World"
Top comments (1)
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?