skip to Main Content

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?

2

Answers


  1. You don’t need Jquery to do that, You can use plain Javascript if you want:

    let url = 'https://example.com?P25hbWU9ZnJlZCZkZXNjcmlwdG9yPUJvc3M='
    let encodedUrl = url.split('?')[1]
    let decoded = atob(encodedUrl)
    let arrValues = decoded.split('&')
    console.log('Name', arrValues[0].split('=')[1])
    console.log('Description', arrValues[1].split('=')[1])
    

    Just remember to use the atob function https://developer.mozilla.org/en-US/docs/Web/API/Window/atob

    Login or Signup to reply.
  2. 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 entries = new URLSearchParams(decodedQuery).entries()
    
    for (const [key, value] of entries) {
      console.log(`${key}, ${value}`);
    }
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search