javascript - replace dash (hyphen) with a space

JavascriptRegex

Javascript Problem Overview


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.

Javascript Solutions


Solution 1 - Javascript

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.

Solution 2 - Javascript

replace() returns an new string, and the original string is not modified. You need to do

str = str.replace(/-/g, ' ');

Solution 3 - Javascript

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, ' ');

Solution 4 - Javascript

var str = "This-is-a-news-item-";
while (str.contains("-")) {
  str = str.replace("-", ' ');
}
alert(str);

I found that one use of str.replace() would only replace the first hyphen, so I looped thru while the input string still contained any hyphens, and replaced them all.

http://jsfiddle.net/LGCYF/

Solution 5 - Javascript

In addition to the answers already given you probably want to replace all the occurrences. To do this you will need a regular expression as follows :

str = str.replace(/-/g, ' ');  // Replace all '-'  with ' '

Solution 6 - Javascript

Use replaceAll() in combo with trim() may meet your needs.

const str = '-This-is-a-news-item-';
console.log(str.replaceAll('-', ' ').trim());

Solution 7 - Javascript

Imagine you end up with double dashes, and want to replace them with a single character and not doubles of the replace character. You can just use array split and array filter and array join.

var str = "This-is---a--news-----item----";

Then to replace all dashes with single spaces, you could do this:

var newStr = str.split('-').filter(function(item) {
  item = item ? item.replace(/-/g, ''): item
  return item;
}).join(' ');

Now if the string contains double dashes, like '----' then array split will produce an element with 3 dashes in it (because it split on the first dash). So by using this line:

item = item ? item.replace(/-/g, ''): item

The filter method removes those extra dashes so the element will be ignored on the filter iteration. The above line also accounts for if item is already an empty element so it doesn't crash on item.replace.

Then when your string join runs on the filtered elements, you end up with this output:

"This is a news item"

Now if you were using something like knockout.js where you can have computer observables. You could create a computed observable to always calculate "newStr" when "str" changes so you'd always have a version of the string with no dashes even if you change the value of the original input string. Basically they are bound together. I'm sure other JS frameworks can do similar things.

Solution 8 - Javascript

if its array like

 arr = ["This-is-one","This-is-two","This-is-three"];
    arr.forEach((sing,index) => {
      arr[index] = sing.split("-").join(" ")
      });

Output will be

['This is one', 'This is two', 'This is three']

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionCMIVXXView Question on Stackoverflow
Solution 1 - JavascriptMartijnView Answer on Stackoverflow
Solution 2 - JavascriptiagreenView Answer on Stackoverflow
Solution 3 - JavascriptRohit JainView Answer on Stackoverflow
Solution 4 - JavascriptZackView Answer on Stackoverflow
Solution 5 - JavascriptHBPView Answer on Stackoverflow
Solution 6 - JavascriptPenny LiuView Answer on Stackoverflow
Solution 7 - JavascriptRyan MannView Answer on Stackoverflow
Solution 8 - JavascriptMuhammad RameezView Answer on Stackoverflow