replace all dashes with sapces in javascript

To replace all dashes with spaces in a string in JavaScript, we can use the replace() method with a regular expression as follows:

index.tsx
let str = "hello-world";
str = str.replace(/-/g, " "); // replace all dashes with spaces
console.log(str); // "hello world"
124 chars
4 lines

In the code above, we first initialize a string variable str with the value "hello-world". We then use the replace() method on this string with a regular expression /-/g as the search pattern and " " (a space) as the replacement. The regular expression /-/g matches all occurrences of the dash character - in the string. The /g flag specifies that the search should be global, i.e., it should match all occurrences of the pattern in the string. Finally, we assign the result of the replace() method back to the str variable and log it to the console, which outputs "hello world".

gistlibby LogSnag