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

2 Answers 2

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");
Sign up to request clarification or add additional context in comments.

2 Comments

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: Don't know what to tell you, the above works for the characters you quoted in your question: jsfiddle.net/g5rgnLu5
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 "-".

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.