首页 > 解决方案 > 如何从 decodeURI(encodeURIComponent(originalString)) 中恢复?

问题描述

现在,我遇到了无法使用的部分解码的 URL 组件。我需要它完全解码。

我不能decodeURIComponent在部分解码的字符串上使用,因为原始字符串可能包含 a %,在这种情况下,它%已经在部分解码的字符串中被解码,这会导致decodeURIComponent与 a 一起崩溃Uncaught URIError: URI malformed

我的选择似乎是:

有没有我还没有想到的不那么丑陋的解决方案?

编辑:有人问我部分决定字符串的含义的例子

const original = 'A-Za-z0-9;,/?:@&=+$-_.!~*()#%';
const encodedURIComponent = encodeURIComponent(original); // "A-Za-z0-9%3B%2C%2F%3F%3A%40%26%3D%2B%24-_.!~*()%23%25"
console.log(decodeURIComponent(encodedURIComponent)); //  "A-Za-z0-9;,/?:@&=+$-_.!~*()#%"
const partiallyUnescaped = decodeURI(encodedURIComponent); // "A-Za-z0-9%3B%2C%2F%3F%3A%40%26%3D%2B%24-_.!~*()%23%" - notice the '%25' at the end was decoded back to '%'
console.log(unescape(partiallyUnescaped)); // "A-Za-z0-9;,/?:@&=+$-_.!~*()#%"
//console.log(decodeURIComponent(partiallyUnescaped)); // error

编辑 2:如果它有任何帮助,这里有一个更现实的例子,说明我们的 URL 可能包含的一些字符,但是因为它是用户生成的,所以它可以是任何东西:

  console.log(                             encodeURIComponent('abcd+%;- efgh'))  ; // "abcd%2B%25%3B-%20efgh"
  console.log(                   decodeURI(encodeURIComponent('abcd+%; -efgh'))) ; // "abcd%2B%%3B- efgh"
//console.log(decodeURIComponent(decodeURI(encodeURIComponent('abcd+%; -efgh')))); // Error: URI malformed

标签: javascriptencodeuricomponentdecodeuricomponent

解决方案


推荐阅读