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

查看:175
本文介绍了比较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规范化slevithan指出。

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

我使用slevithan建议的规范化lib分叉我原来的jsfiddle来创建一个版本。链接: 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天全站免登陆