为什么用Javascript字符串替换会颠倒从右到左语言的单词顺序? [英] Why does Javascript string replace reverse the word order for right to left languages?

查看:91
本文介绍了为什么用Javascript字符串替换会颠倒从右到左语言的单词顺序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很好奇为什么以下占位符替换为从右到左的语言(这些是随机的阿拉伯字符)会导致格式化后的字符串将所有单词颠倒.

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}', 'هلهل')
=> "هلهل تكنولوجيا"

在最新的Chrome,FF和Safari中观察到此行为.它使单词顺序在Node中保持不变.

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

推荐答案

不是. replace完全按照您的要求执行:用هلهل替换该字符串的前三个字母;我将其设置为四个而不是三个,以便原始和替换的长度相同(以便更轻松地查看正在发生的情况):

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;
}

输出:


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

请注意,替换序列(U-0647,U-0644,U-0647,U-0644)现在位于字符串的开头.

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

您所看到的是字符串显示的方式.因为RTL字符的连续范围是从右到左显示的,所以您现在有一个RTL范围,它以这种方式显示:替换在开头(最右边),文本继续在左边.以前,您对LTR和RTL有误,这与LTR(从左至右显示)和RTL(从右至左显示)一起显示.

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).

这篇关于为什么用Javascript字符串替换会颠倒从右到左语言的单词顺序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆