3

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();

2 Answers2

4

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");
Community
  • 1
  • 1
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • I've tried using the above code to replace the longer - with the shorter one. It didn't work out. The reason that I want to replace the longer one is that I have another code running that separates the words at the "-". The code scans for the "-" and then CAPITALIZES the words before the "-". But since the "-" is not getting replaced, the code stops to work. I've edited the question to include this code as well. – Chordzone.org Oct 03 '16 at 05:34
  • @Chordzone.org: Don't know what to tell you, the above works for the characters you quoted in your question: https://jsfiddle.net/g5rgnLu5/ – T.J. Crowder Oct 03 '16 at 05:54
1

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

Barry Michael Doyle
  • 9,333
  • 30
  • 83
  • 143