javascript - replace dash (hyphen) with a space
replace()
returns an new string, and the original string is not modified. You need to do
str = str.replace(/-/g, ' ');
I think the problem you are facing is almost this: -
str = str.replace("-", ' ');
You need to re-assign the result of the replacement to str
, to see the reflected change.
From MSDN Javascript reference: -
The result of the replace method is a copy of stringObj after the specified replacements have been made.
To replace all the -
, you would need to use /g
modifier with a regex parameter: -
str = str.replace(/-/g, ' ');
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
g
flag, for 'global', so that all instances will be replaced.