Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Javascript string replace reverse the word order for right to left languages?

I'm curious as to why the following placeholder replacement for a right to left language (these are random Arabic characters) causes the formatted string to reverse all the words.

'{0} تكنولوجيا'.replace('{0}', 'هلهل')
=> "هلهل تكنولوجيا"

This behavior was observed in the latest Chrome, FF, and Safari. It keeps the word order the same in Node.

like image 881
Adam Gotterer Avatar asked Aug 16 '16 14:08

Adam Gotterer


1 Answers

It doesn't. replace does exactly what you asked it to do: Replaces the first three letters of that string with هلهل; I'm going to make it four rather than three so the original and the replacement are the same length (makes it easier to see what's going on):

var before = '{00} تكنولوجيا';
var rep = 'هلهل';
var after = before.replace('{00}', rep);
console.log("before", before.split("").map(toCharCode).join(", "));
console.log("rep   ", rep.split("").map(toCharCode).join(", "));
console.log("after ", after.split("").map(toCharCode).join(", "));

function toCharCode(c) {
  var hex = c.charCodeAt(0).toString(16);
  hex = "0000".substr(hex.length - 4) + hex;
  return "U-" + hex;
}

Output:

before U-007b, U-0030, U-0030, U-007d, U-0020, U-062a, U-0643, U-0646, U-0648, U-0644, U-0648, U-062c, U-064a, U-0627
rep    U-0647, U-0644, U-0647, U-0644
after  U-0647, U-0644, U-0647, U-0644, U-0020, U-062a, U-0643, U-0646, U-0648, U-0644, U-0648, U-062c, U-064a, U-0627

Note that the replacement sequence (U-0647, U-0644, U-0647, U-0644) is now at the beginning of the string.

What you're seeing is the way the string is displayed. Because contiguous spans of RTL characters are displayed right-to-left, and you now have a single span of RTL which is shown in that way: The replacement is at the beginning (the far right) and the text continues to the left. Before, you had a mis of LTR and RTL, which was shown with the LTR (shown from left to right) followed by the RTL (shown from right to left).

like image 149
T.J. Crowder Avatar answered Oct 06 '22 01:10

T.J. Crowder