javascripthtmlright-to-leftbidileft-to-right

Weird behaviour when using replace on arab string


I am trying to understand why in this snippet, for a given string

عروض تبدأ من $minprice

I get

عروض تبدأ من $5821

back :(

Any help would be much appreciated! Thanks :)

var regExp = new RegExp(/\$minprice/, 'ig');
var string = "عروض تبدأ من $minprice";

console.group();
console.log(
  "new string",
  string.replace(regExp, (matched, offset, originalString) => {
    console.log('originalString', originalString);
    return '$5821';
  })
);
console.groupEnd();

Solution

  • Probably, you are upset that the $ sign goes to the right of the number. Don't despair: if you make a Web search, you will find many respectable sites in Arabic where the relative positions of $ and the western digits are this way, or even mixed $123 and 123$ on the same page.

    As for the order of tokens, the result is absolutely correct, the readers will expect the price to be to the left of the words, because Arabic is RTL language. In many countries, they would also expect to see the Hindic digits, but maybe not with USD sugn attached.

    The position of the dollar sign relative to the digits depends on the directionality of the span. I.e. if you wrap your the string in <span dir="rtl">, it will look different from <span dir="ltr">. You can try to return '$5821' and '5821$' and find which one looks best to you.