开发者

Concat strings for right to left locales in javascript

It seems + is not the right operator to handle the concatenation of strings in JavaScript.开发者_开发百科 what are some alternatives to handle the both the ltr and rtl cases?


The problem is, + is not right operator to concatenate strings at all. Or maybe it is, but concatenating string is an Internationalization bug.

Instead of simply concatenating them, one should actually format them. So what you should actually do, is use placeholders:

var somePattern = "This language is written {0}.";
var someMessage = somePattern.format("LTR");

This way, the translator would be able to re-order the sentence, including word order. And I believe it solves your problem.

For formatting function, let me quote this excellent answer:

String.prototype.format = function() {
    var args = arguments;

    return this.replace(/\{(\d+)\}/g, function() {
        return args[arguments[1]];
    });
};

EDIT: Adding information about directionality marks.

Sometimes, when you have multiple placeholders you may lose the control of string direction, i.e. {0}/{1} would still be shown as first/second instead of desired second/last. To fix this, you would add Strong Directionality Mark to the pattern, i.e. {0}‏/{1}. ‏ is an HTML entity that resolves to Unicode code point U+200F, that is right-to-left strong directionality mark.


Actually, assuming both string are localized and you want the string on the right to be displayed logically after the string on the left, then + sometimes works fine. Strings in languages such as Arabic should be displayed RTL (right to left) on the screen, but the character ordering is still meant to be LTR (left to right) in memory. So + operator is logically consistent to use for generating an 'ordered list' of terms in any language.

But there are also scenarios where + does not solve the problem correctly. There are scenarios where the correct solution is to follow the grammar of the containing language. For instance, are you really embedding an English word in an Arabic sentence? Or vice versa? Regardless, the solution here is to do string formatting, where the containing sentence localized has a placeholder for the foreign term, like {0}.

The third case is what if there is no grammatical relationship because it is just two separate sentences? In this case there is no correct ordering. E.g. if you have an English sentence displayed in front of an Arabic sentence. An English speaker will probably read the sentences LTR (left sentence first, then right). An Arabic speaker will probably read the sentences RTL. Either way it's unclear to everyone which order the author intended the sentences to be read in. :)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜