简体   繁体   中英

Mutually exclusive url encoding between encodeURIComponent and encodeURI?

This is a problem that is somewhat specific to react-router . Let say we have a blog post with an id of: id%20/something . This id is not encoded.

When navigating to the detail page of the blog post, I want to put the id into the path. The route patters looks like this (this time I'm encoding with encodeURIComponent ):

blog/post/id%2520%2Fsomething

With react router we can access our route parameters with a hook called useParams . This function will auto-decode url parameters using decodeURI resulting in a parameter value:

id%20%2Fsomething

As you can see the / was not correctly decoded and is still present as %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,
)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM