jquerybase64

Decode base64 url parameters with jquery


I want to be able to take a base64 encoded url string and retrieve the name and descriptor parameter values from it in jquery.

I have it working with the parameters not base64 encoded by getting the url string as an array and then lifting out the values of the 2 parameters (name and descriptor) - but when I base64 encode the parameters in the url, I can decode the string, but it comes back as a string and not an array so I cant lift out the values of the name and descriptor parameters.

so url would be https://example.com?name=fred&descriptor=Boss and encoded to base64 https://example.com?P25hbWU9ZnJlZCZkZXNjcmlwdG9yPUJvc3M=

So from https://example.com?P25hbWU9ZnJlZCZkZXNjcmlwdG9yPUJvc3M= how can I get the values of name and descriptor in jquery and set them as variables?

Maybe its easier to not get an array from the decoded version, and just use jquery to get the values after the "+" atob decoding?


Solution

  • Another solution inspired by @Hackerman's answer with URL and URLSearchParams. Note that this solution rely on native API without any need of magic string:

    const url = 'https://example.com?P25hbWU9ZnJlZCZkZXNjcmlwdG9yPUJvc3M='
    const encodedUrl = new URL(url);
    const decodedQuery = atob(encodedUrl.searchParams); 
    const params = new URLSearchParams(decodedQuery)
    
    // get name and descriptor
    fetchedName = params.get("name");
    fetchedDescriptor = params.get("descriptor");
    
    console.log(fetchedName)
    console.log(fetchedDescriptor)
    
    // get all entries
    const entries = new URLSearchParams(decodedQuery).entries()
    
    for (const [key, value] of entries) {
      console.log(`${key}, ${value}`);
    }