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:
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.
This fixes it:
let str = "This-is-a-news-item-"; str = str.replace(/-/g, ' '); alert(str);
There were two problems with your code:
- First, String.replace() doesn’t change the string itself, it returns a changed string.
- Second, if you pass a string to the replace function, it will only replace the first instance it encounters. That’s why I passed a regular expression with the
gflag, for ‘global’, so that all instances will be replaced.