5

此代码与 nodejs v0.10.21 中断

#!/usr/bin/env node
"use strict";

var urlEncoded = 'http://zh.wikipedia.org/wiki/%F0%A8%A8%8F';
var urlDecoded = decodeURI( urlEncoded );
var urlLeafEncoded = urlEncoded.substr( 29 );
var urlLeafDecoded = decodeURIComponent( urlLeafEncoded );
var urlLeafFirstCharacterDecoded = urlLeafDecoded.charAt( 0 );
var urlLeafFirstCharacterEncoded = encodeURIComponent( urlLeafFirstCharacterDecoded );

console.log( 'URL encoded = ' + urlEncoded );
console.log( 'URL decoded = ' + urlDecoded );
console.log( 'URL leaf encoded = ' + urlLeafEncoded );
console.log( 'URL leaf decoded = ' + urlLeafDecoded );
console.log( 'URL leaf first character encoded = ' + urlLeafEncoded );
console.log( 'URL leaf first character decoded = ' + urlLeafDecoded );

我收到以下错误

var urlLeafFirstCharacterEncoded = encodeURIComponent( urlLeafFirstCharacterDe
                               ^
URIError: URI malformed
    at encodeURIComponent (native)
    at Object.<anonymous> (/media/data/tmp/mwoffliner/test.js:9:36)
    at Module._compile (module.js:456:26)
    at Object.Module._extensions..js (module.js:474:10)
    at Module.load (module.js:356:32)
    at Function.Module._load (module.js:312:12)
    at Function.Module.runMain (module.js:497:10)
    at startup (node.js:119:16)
    at node.js:901:3

Javascript 用于正确处理多字节字符,但在这种情况下并非如此。看起来虽然“%F0%A8%A8%8F”代表一个汉字,但javascript认为它们是其中的两个。如果这是 javascript 运行时中的错误,不知是编码问题,还是我这边的误解,我感到很困惑。

4

1 回答 1

4

位于 BMP 之外,并且由于 Javascript 仅使用 2 个字节来存储字符,因此表示为surrogate pair。虽然encodeURIComponent可以对代理项对进行操作并为它们生成正确的 UTF8 编码,但它不能单独读取代理项。因此,虽然encodeURIComponent("")工作正常,但encodeURIComponent("".charAt(0))会失败。

有关详细信息,请参阅http://mathiasbynens.be/notes/javascript-encoding 。此外,https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURIComponent专门记录了这个用例。

于 2013-11-03T13:47:09.307 回答