javascript – replace dash (hyphen) with a space

This fixes it:

let str = "This-is-a-news-item-";
str = str.replace(/-/g, ' ');
alert(str);

There were two problems with your code:

  1. First, String.replace() doesn’t change the string itself, it returns a changed string.
  2. 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.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)