javascript - 当字符串不是字符串时? Javascript中的Unicode规范化怪异

标签 javascript string firefox unicode unicode-normalization

对我来说,在使用 .normalize() 时,我遇到了 Firefox 中字符串行为的一些严重异常。 Unicode 规范化函数。

Here是一个demo,在Firefox中查看控制台就可以看到问题了。

假设我有一个 id 为“NFKC”的按钮:

<button id="NFKC">NFKC</button>

得到一个引用,很容易:

document.querySelector('#NFKC')
// <button id="NFKC">

现在,由于此按钮的 id 为 NFKC,我们可以按如下方式获取该字符串:

document.body.querySelector('#NFKC').id
// "NFKC"

将该字符串粘贴到变量中:

var s1 = document.body.querySelector('#NFKC').id

作为比较,直接将相同的字符串分配给变量:

var s2 = 'NFKC'

所以当然:

s1 === s2
// true

和:

s1 == s2
// true

现在是我的头爆炸的部分。

要规范化字符串,请传递 NFC 之一, NFD , NFKC , 或 NFKD.normalize() , 像这样:

'á'.normalize('NFKC')
// "á"

当然,根据您选择的规范化形式,您会得到不同的代码点,但无论如何。

'á'.normalize('NFC').length == 1
// true
'á'.normalize('NFD').length == 2
// true

但是无所谓。关键是,将对应于规范化形式的四个字符串之一传递给 .normalize() ,你会得到一个标准化的字符串。

因为我们知道 s1 (我们从 DOM 中检索到的字符串)和 s2是相同的字符串( s1 === s2true ),那么显然我们可以使用任何一个来规范化字符串:

'á'.normalize(s2)
"á"
// well yeah, because s2 IS 'NFKC'. 

当然,s1行为会完全一样,对吧?

'á'.normalize(s1)
 // RangeError: form must be one of 'NFC', 'NFD', 'NFKC', or 'NFKD'

没有。

所以问题是:为什么会出现 s1不等于 s2.normalize()关心,当s1 === s2是真的?

这不会发生在 Chrome 中,这是我迄今为止测试过的唯一其他浏览器。

更新

这是 Firefox 和 has been fixed 中的一个错误。 .

最佳答案

我不确定这是否会有所帮助,但文档指出

This is an experimental technology, part of the Harmony (ECMAScript 6) proposal. Because this technology's specification has not stabilized, check the compatibility table for usage in various browsers. Also note that the syntax and behavior of an experimental technology is subject to change in future version of browsers as the spec changes.



兼容性表是
Feature         Chrome  Firefox (Gecko) Internet Explorer           Opera   Safari
Basic support   34      31 (31)         11 on Windows 10 Preview    (Yes)   Not supported

但是,此页面的最后一次更新是 2014 年 11 月 18 日。

关于javascript - 当字符串不是字符串时? Javascript中的Unicode规范化怪异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29153533/

相关文章:

c# - C#中使用字符串调用变量

python - 如果没有 Marionette,Geckodriver/Firefox 如何工作? (针对 FF 53 运行 python selenium 3)

javascript - 在 Javascript 处理后产生截然不同的 HTML 的示例网站

firefox - 如何在 Selenium Webdriver 中设置特定的 Firefox 版本?

javascript - 在 JavaScript 中通过 ID 引用 ASP.NET 控件?

javascript - 视口(viewport)右下边缘的 x、y 位置(分别)?

c - 对数组中的 2 个字符串进行排序并将它们合并为 C 中的一个

string - 将 NSDate 转换为 NSString 时设置了错误的年份

javascript - AngularJS 在 ng-change 调用的函数中将属性值作为参数传递

javascript - 打印样式表不影响使用 javascript