Search code examples
javascriptreactjsurldecode

get raw value from URL parameter in reactjs


I've got a react component that allows users to unsubscribe from an email, and there's a hash being passed along with the unsubscribe link so we know what mail item the request is associated with. Unfortunately the hash sometimes has some URL-specific characters in it, like + and /. Right now I'm doing something like this to get the data from the hash to pass to the unsubscribe service:

const query = new URLSearchParams(useLocation().search);
const campaignId = query.get('campaign') ?? '';

the problem is that when I pass the campaign in to the unsubscribe, and (for example) the campaig hash has a + in it, that gets converted to a space.

Is there a better way to get this string, or a way to "un-encode" it?


Solution

  • I ended up doing something fairly inelegant-- but it works. I used the decodeURIComponent() as suggested by @ofri in the comments above, but the spaces were not being converted back to +. So this is what I came up with:

    const query = new URLSearchParams(useLocation().search);
    const campaignId = query.get('campaignId') ?? '';
    
    // then when we create the axios payload:
    campaignId : decodeURIComponent(campaignId.replace(/ /g, '+'))