- Instant help with your JavaScript coding problems

Replace spaces with dashes in JavaScript

Question:
How to replace spaces with dashes in JavaScript?
Answer:
let originalText = 'This is my text';
let dashedText = originalText.replace(/ /g, '-');

console.log('Original: ' + originalText);
console.log('Dashed: ' + dashedText);
Description:

The replace() method returns a new string with some or all matches of a pattern replaced by a replacement. The pattern can be a string or a RegExp, and the replacement can be a string or a function to be called for each match. If the pattern is a string, only the first occurrence will be replaced.

Reference:
replace() manual
Share "How to replace spaces with dashes in JavaScript?"
Tags:
javascript, string, replace, replace all, regexp
Technical term:
Replace spaces with dashes in JavaScript