To replace all dashes with spaces in a string in JavaScript, we can use the replace()
method with a regular expression as follows:
index.tsx124 chars4 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