问题描述
- 我有一些旧代码(预先反应),可以在https://www.npmjs.com/package/history模块上调用
encodeURIComponent
之前使用history.push()
对URL的一部分进行编码,以便导航到该URL。 li>
-
history.push()
内的history.js
然后使用decodeURI
部分解码整个URL(decodeURI
仅解码encodeURI
编码的相同字符) - 此部分解码的位置。路径名最终出现在ReactRouter中,其中
useParams()
再次给了我部分解码的URL组件。
现在,我陷入了无法使用的部分解码URL组件的困境。我需要将其完全解码。
我不能在部分解码的字符串上使用decodeURIComponent
,因为原始字符串可能包含%
,在这种情况下,此%
将已经在部分解码的字符串中解码这将导致decodeURIComponent
崩溃并导致Uncaught URIError: URI malformed
。
我的选择似乎是:
- 即使不鼓励使用
unescape
,也可以完全解码部分解码的字符串(它不会抱怨单个%
)(为什么?) - 手动将所有
%
(后跟数字和后跟的十六进制字符)重新编码回%25
,然后通过decodeURIComponent
运行结果
有没有我想不到的丑陋解决方案?
编辑:有人问我有关部分确定的字符串的含义的示例
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
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)