Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript - replace dash (hyphen) with a space

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.

like image 887
CMIVXX Avatar asked Jan 10 '13 16:01

CMIVXX


People also ask

How do you replace a hyphen in space?

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!

What is /\ s +/ G?

\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.

How do you replace a space in JavaScript?

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.

How do you add a hyphen in JavaScript?

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' .


1 Answers

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.
like image 132
Martijn Avatar answered Sep 20 '22 10:09

Martijn