I have been looking for this for a while, and while I have found many responses for changing a space into a dash (hyphen), I haven't found any that go the other direction.
Initially I have:
var str = "This-is-a-news-item-";
I try to replace it with:
str.replace("-", ' ');
And simply display the result:
alert(str);
Right now, it doesn't do anything, so I'm not sure where to turn. I tried reversing some of the existing ones that replace the space with the dash, and that doesn't work either.
Thanks for the help.
Replace Spaces with Dashes in a String using replace() # To replace the spaces with dashes in a string, call the replace() method on the string, passing it the following regular expression - /\s+/g and a dash as parameters. The replace method will return a new string, where each space is replaced by a dash. Copied!
\s means "one space", and \s+ means "one or more spaces". But, because you're using the /g flag (replace all occurrences) and replacing with the empty string, your two expressions have the same effect. Follow this answer to receive notifications.
Use the String. replace() method to replace all spaces in a string, e.g. str. replace(/ /g, '+'); . The replace() method will return a new string with all spaces replaced by the provided replacement.
To insert hyphens into a JavaScript string, we can use the JavaScript string's replace method. We call phone. replace with a regex that has 3 capturing groups for capturing 2 groups of 3 digits and the remaining digits respectively. Then we put dashes in between each group with '$1-$2-$3' .
This fixes it:
let str = "This-is-a-news-item-"; str = str.replace(/-/g, ' '); alert(str);
There were two problems with your code:
g
flag, for 'global', so that all instances will be replaced.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With