how to fix this right-to-left script issue in js string?

女生的网名这么多〃 提交于 2021-01-28 08:48:20

问题


I would like the default behavior instead of this right-to-left script issue when using the strange string.

I cannot even type the expected output in the question. The browser automatically puts it in the wrong side.

var strange = "د.إ";
var common = "$";

var amount = 50;
var str_common = common + amount;
var str_strange = strange + amount;

alert(str_common);

// unexpected output
alert(str_strange);

// unexpected output
alert(str_common + ' -- ' + str_strange);

// unexpected output
alert(str_strange + ' -- ' + str_common);

js fiddle - http://jsfiddle.net/rahulroy9202/xL7cu2os/1/


回答1:


You could make use of the unicode control character U+202A to force it LTR:

var str_strange = '\u202A' + strange + amount;

\u202A is the unicode control character for LTR embedding. \u202B is for RTL embedding.

More info here: https://en.wikipedia.org/wiki/Bi-directional_text#Table_of_possible_BiDi-types

You could also use the \u200.. series. Just use \u200E for forcing it to LTR.

Snippet (with comnbinations):

var strange = "د.إ", common = "$", amount = 50, strStrange = '';
strStrange = '\u202A' + strange + amount;
alert(strStrange);
strStrange = '\u200E' + strange + '\u200E' + amount;
alert(strStrange);


来源:https://stackoverflow.com/questions/32710566/how-to-fix-this-right-to-left-script-issue-in-js-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!