[Javascript] How to replace all spaces with `-` in a given string?


I want to replace all the spaces with '-', for example., 'this is a test message' to 'this-is-a-test-message'. How can I do that in Javascript?

1 Answer

3 years ago by

Use replace() method along with regex / /g to replace all spaces. If you forget to include g it will replace only the first white space.

let str = 'this is a test message';

console.log(str.replace(/ /, "-"));
console.log(str.replace(/ /g, "-"));

Run here https://onecompiler.com/javascript/3xnru9efy

3 years ago by Meera