Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

replace – with - using replace()

I have been using

var str = "Artist - Song";
str = str.replace("-", "feat");

to change some texts to "-".

Recently, I've noticed another "–" that the above code fails to replace. This "–" seems a bit longer than the normal "-".

Is there any way to replace the longer one with the shorter "-"? Any help is appreciated. Thanks

EDIT.

This is how the rest of the code is written.

  var befComma = str.substr(0, str.indexOf('-'));
    befComma.trim();
    var afterhyp = str.substr(str.indexOf("-") + 1);
   var changefeat =  befComma.toUpperCase();
like image 672
Chordzone.org Avatar asked Aug 25 '26 21:08

Chordzone.org


2 Answers

This "–" seems a bit longer than the normal "-".

Is there any way to replace the longer one with the shorter "-"?

Sure, you just do the same thing:

str = str.replace("–", "-");

Note that in both cases, you'll only replace the first match. If you want to replace all matches, see this question's answers, which point you at regular expressions with the g flag:

str = str.replace(/-/g, "feat");
str = str.replace(/–/g, "-");

I'm not quite sure why you'd want to replace the longer one with the shorter one, though; don't you want to replace both with feat?

If so, this replaces the first:

str = str.replace(/[-–]/, "feat");

And this replaces all:

str = str.replace(/[-–]/g, "feat");
like image 74
T.J. Crowder Avatar answered Aug 29 '26 16:08

T.J. Crowder


Give this a shot:

var str = "Artist – Song";
str = str.replace("–", "-"); // Add in this function
str = str.replace("-", "feat");

This should replace the slightly longer "–" with the shorter more standard "-".

like image 37
Barry Michael Doyle Avatar answered Aug 29 '26 14:08

Barry Michael Doyle



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!