gpt4 book ai didi

javascript - encodeURIComponent 抛出异常

转载 作者:行者123 更新时间:2023-11-29 16:15:28 25 4
gpt4 key购买 nike

我在 encodeURIComponent 函数的帮助下使用用户提供的输入以编程方式构建 URI。但是,当用户输入无效的 unicode 字符(例如 U+DFFF)时,该函数会抛出异常并显示以下消息:

The URI to be encoded contains an invalid character

我在 MSDN 上查过这个,但这并没有告诉我任何我不知道的事情。

To correct this error

  • Ensure the string to be encoded contains only valid Unicode sequences.

我的问题是,在将用户提供的输入传递给 encodeURIComponent 函数之前,是否有办法清除所有无效的 Unicode 序列?

最佳答案

采用编程方法来发现答案,唯一出现问题的范围是\ud800-\udfff,即高代理项和低代理项的范围:

for (var regex = '/[', firstI = null, lastI = null, i = 0; i <= 65535; i++) {
try {
encodeURIComponent(String.fromCharCode(i));
}
catch(e) {
if (firstI !== null) {
if (i === lastI + 1) {
lastI++;
}
else if (firstI === lastI) {
regex += '\\u' + firstI.toString(16);
firstI = lastI = i;
}
else {
regex += '\\u' + firstI.toString(16) + '-' + '\\u' + lastI.toString(16);
firstI = lastI = i;
}
}
else {
firstI = i;
lastI = i;
}
}
}

if (firstI === lastI) {
regex += '\\u' + firstI.toString(16);
}
else {
regex += '\\u' + firstI.toString(16) + '-' + '\\u' + lastI.toString(16);
}
regex += ']/';
alert(regex); // /[\ud800-\udfff]/

然后我用一个更简单的例子证实了这一点:

for (var i = 0; i <= 65535 && (i <0xD800 || i >0xDFFF ) ; i++) {
try {
encodeURIComponent(String.fromCharCode(i));
}
catch(e) {
alert(e); // Doesn't alert
}
}
alert('ok!');

这符合 MSDN 的说法,因为除了代理之外,所有这些 Unicode 字符(甚至是有效的 Unicode“非字符”)都是有效的 Unicode 序列。

您确实可以过滤掉高和低代理项,但是当在高低对中使用时,它们就变得合法(因为它们旨在以这种方式使用以允许 Unicode 扩展(大幅)超出其原始最大值字符数):

alert(encodeURIComponent('\uD800\uDC00')); // ok
alert(encodeURIComponent('\uD800')); // not ok
alert(encodeURIComponent('\uDC00')); // not ok either

因此,如果您想采取简单的方法并阻止代理人,只需:

urlPart = urlPart.replace(/[\ud800-\udfff]/g, '');

如果您想去除不匹配(无效)的代理,同时允许代理对(这是合法的序列,但很少需要这些字符),您可以执行以下操作:

function stripUnmatchedSurrogates (str) {
return str.replace(/[\uD800-\uDBFF](?![\uDC00-\uDFFF])/g, '').split('').reverse().join('').replace(/[\uDC00-\uDFFF](?![\uD800-\uDBFF])/g, '').split('').reverse().join('');
}

var urlPart = '\uD801 \uD801\uDC00 \uDC01'
alert(stripUnmatchedSurrogates(urlPart)); // Leaves one valid sequence (representing a single non-BMP character)

如果 JavaScript 具有负向后视功能,该函数将不那么丑陋......

关于javascript - encodeURIComponent 抛出异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16868415/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com