javascript - 如何从 decodeURI(encodeURIComponent(originalString)) 中恢复?
问题描述
encodeURIComponent
在调用https://www.npmjs.com/package/history模块以导航到该 URL之前history.push()
,我有一些遗留代码(pre-React)对 URL 的一部分进行编码。history.push()
insidehistory.js
然后用于decodeURI
部分解码整个 URL(仅解码与编码decodeURI
相同的字符)encodeURI
- 这个部分解码的 location.pathname 最终在 ReactRouter 中返回
useParams()
给我部分解码的 URL 组件。
现在,我遇到了无法使用的部分解码的 URL 组件。我需要它完全解码。
我不能decodeURIComponent
在部分解码的字符串上使用,因为原始字符串可能包含 a %
,在这种情况下,它%
已经在部分解码的字符串中被解码,这会导致decodeURIComponent
与 a 一起崩溃Uncaught URIError: URI malformed
。
我的选择似乎是:
- 用于
unescape
完全解码部分解码的字符串(它不会抱怨 single%
),即使不鼓励使用它(为什么?) %
手动将任何(后面没有数字和随后的十六进制字符)重新编码回%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
解决方案
推荐阅读
- javascript - 单击时导入 SaSS - 单击时刷新并应用
- python - 当我尝试 pip install openbte 时出现特定错误
- python - 如何使用索引调用其他数据框数据
- angular - http 请求的 Angular 接口:JSON 键并不总是相同
- python - 以一种奇怪的方式拆分 csv
- jquery - 何时在 jQuery 中使用 filter() 与 :?
- selenium - 为 Firefox 创建一个虚假的网络摄像头流
- css - 覆盖内联样式
- javascript - 将变量放入 a href 标记
- python - Python 3.7.1 尝试除了在命令行中以错误顺序发生的块