Replacing unknown special characters from string using JavaScript

Viewed 571

I have a string which has a special character — this is called em-dash. I want to replace this character from my string using javascript, in both Windows and Linux.

It works well in Windows and I used this

mystring.replace(/—/, "-");

works, but in Linux that character — em-dash is shown as a black diamond with a question mark �

How do I match this character and replace to something?

\u2014 = em-dash unicode

let string = 'SampleTestcase—Temp';

if (string.match("\u2014")) {
     console.log("YES ITS MATCHED and its Em-dash");
     string = string.replace("\u2014", "-");
}

console.log(string);

My Expected Output is SampleTestcase-Temp;

Also, why Linux shows em-dash as a black diamond with a question mark and sometimes it showing like a comma?

1 Answers

Just skip the quotes passing only the Unicode to the regex argument (between //), and use g flag:

console.log('SampleTestcase———————Temp'.replace(/\u2014/g, '-'));

Related