这是一个特定于
react-router
的问题。假设我们有一篇博客文章,ID 为:id%20/something
。该 ID 未编码。
当导航到博客文章的详细信息页面时,我想将id放入路径中。路线模式看起来像这样(这次我使用
encodeURIComponent
进行编码):
blog/post/id%2520%2Fsomething
使用 React Router,我们可以使用名为
useParams
的钩子访问路由参数。此函数将使用 decodeURI
自动解码 url 参数,产生参数值:
id%20%2Fsomething
如您所见,
/
未正确解码,仍然显示为 %2F
。我现在最终得到了编码和解码值的混合。
我正在寻找获得完全解码字符串的最简单方法。
试试这个:
// check all ASCII codepoints if encodeURI and encodeURIComponent treat them
// differently — non-ASCII are always encoded by both functions
const diffs = Array.from({ length: 0x80 }, (_, i) => String.fromCodePoint(i))
.filter((x) => encodeURI(x) !== encodeURIComponent(x))
const re = new RegExp(diffs.map(encodeURIComponent).join('|'), 'g')
function clean(str) {
return str.replace(re, decodeURIComponent)
}
console.log(re) // => /%23|%24|%26|%2B|%2C|%2F|%3A|%3B|%3D|%3F|%40/g
console.log(clean('id%20%2Fsomething')) // => 'id%20/something'
或者,预先计算的版本:
function clean(str) {
return str.replace(
/%23|%24|%26|%2B|%2C|%2F|%3A|%3B|%3D|%3F|%40/g,
decodeURIComponent,
)
}