比较 unicode 字符时,Javascript 字符串比较失败 [英] Javascript string comparison fails when comparing unicode characters

查看:29
本文介绍了比较 unicode 字符时,Javascript 字符串比较失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想比较 JavaScript 中相同的两个字符串,但相等运算符 == 返回 false.一个字符串包含一个特殊字符(例如丹麦语 å).

I want to compare two strings in JavaScript that are the same, and yet the equality operator == returns false. One string contains a special character (eg. the danish å).

JavaScript 代码:

JavaScript code:

var filenameFromJS = "Designhåndbog.pdf";
var filenameFromServer = "Designhåndbog.pdf";

print(filenameFromJS == filenameFromServer); // This prints false why?

解决方案正如斯莱维坦指出的那样,对我有用的是 unicode 规范化.

The solution What worked for me is unicode normalization as slevithan pointed out.

我分叉了我原来的 jsfiddle,使用 slevithan 建议的规范化库制作了一个版本.链接:http://jsfiddle.net/GWZ8j/1/.

I forked my original jsfiddle to make a version using the normalization lib suggested by slevithan. Link: http://jsfiddle.net/GWZ8j/1/.

推荐答案

与这里其他人所说的不同,这与编码无关.相反,您的两个字符串使用不同的代码点来呈现相同的视觉字符.

Unlike what some other people here have said, this has nothing to do with encodings. Rather, your two strings use different code points to render the same visual characters.

要正确解决这个问题,您需要在比较之前对两个字符串执行 Unicode 规范化.不幸的是,JavaScript 没有内置此功能.这是一个可以为您执行规范化的 JavaScript 库:https://github.com/walling/unorm

To solve this correctly, you need to perform Unicode normalization on the two strings before comparing them. Unforunately, JavaScript doesn't have this functionality built in. Here is a JavaScript library that can perform the normalization for you: https://github.com/walling/unorm

这篇关于比较 unicode 字符时,Javascript 字符串比较失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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