3

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?

wscourge
  • 10,657
  • 14
  • 59
  • 80
YuvaMac
  • 419
  • 1
  • 6
  • 13
  • 1
    How are you looking at this character in Linux? What application are you using? – melpomene Jan 08 '19 at 08:47
  • 1
    You do not need to check if there is em-dash in the string when you want to replace it. Just use `string = string.replace(/\u2014/g, '-')`. Actually, melpomene's question is very relevant: how do you display the contents in Linux? Tool? Options? – Wiktor Stribiżew Jan 08 '19 at 08:50
  • Seems to me that your string is in 2 different encodings. – user732456 Jan 08 '19 at 08:52
  • Use same code on Linux, it will work correctly, even if it displays differently (maybe font problem) – ponury-kostek Jan 08 '19 at 08:56

1 Answers1

0

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

console.log('SampleTestcase———————Temp'.replace(/\u2014/g, '-'));
wscourge
  • 10,657
  • 14
  • 59
  • 80