javascriptreactjsreact-router

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.


Solution

  • 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: 0x80 }, (_, i) => String.fromCodePoint(i))
        .filter((x) => encodeURI(x) !== encodeURIComponent(x))
    
    const re = new RegExp(diffs.map(encodeURIComponent).join('|'), 'g')
    
    const clean = (str) => 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'

    Or, a pre-calculated version:

    const clean = (str) => str.replace(
        /%23|%24|%26|%2B|%2C|%2F|%3A|%3B|%3D|%3F|%40/g,
        decodeURIComponent,
    )