[英]Mutually exclusive url encoding between encodeURIComponent and encodeURI?
This is a problem that is somewhat specific to react-router
.这是一个特定于
react-router
的问题。 Let say we have a blog post with an id of: id%20/something
.假设我们有一个 id 为的博客文章:
id%20/something
。 This id is not encoded.此 ID未编码。
When navigating to the detail page of the blog post, I want to put the id into the path.导航到博客文章的详细信息页面时,我想将 id 放入路径中。 The route patters looks like this (this time I'm encoding with
encodeURIComponent
):路由模式如下所示(这次我使用
encodeURIComponent
进行编码):
blog/post/id%2520%2Fsomething
With react router we can access our route parameters with a hook called useParams
.使用 react 路由器,我们可以使用名为
useParams
的钩子访问我们的路由参数。 This function will auto-decode url parameters using decodeURI
resulting in a parameter value:此 function 将使用
decodeURI
自动解码 url 参数,从而产生一个参数值:
id%20%2Fsomething
As you can see the /
was not correctly decoded and is still present as %2F
.如您所见,
/
未正确解码,仍以%2F
的形式存在。 I now ended up with a mix of encoded and decoded values.我现在最终得到了编码和解码值的混合。
I'm looking for the easiest way to arrive at a fully decoded string.我正在寻找最简单的方法来获得完全解码的字符串。
Try this:尝试这个:
// check all ASCII codepoints if encodeURI and encodeURIComponent treat them
// differently — non-ASCII are always encoded by both functions
const diffs = Array.from({ length: 0x7f })
.map((_, i) => String.fromCodePoint(i))
.filter(x => encodeURI(x) !== encodeURIComponent(x))
const re = new RegExp(diffs.map(encodeURIComponent).join('|'), 'g')
const clean = (x) => x.replace(re, decodeURIComponent)
clean('id%20%2Fsomething') // => 'id%20/something'
Or, a pre-calculated version:或者,预先计算的版本:
const clean = (x) => x.replace(
/%23|%24|%26|%2B|%2C|%2F|%3A|%3B|%3D|%3F|%40/g,
decodeURIComponent,
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.