Home > Enterprise >  How to get specific part of url that uses ASCII Encoding Reference?
How to get specific part of url that uses ASCII Encoding Reference?

Time:09-13

I'm currently trying to retrieve the email from an encoded url similar to this:

https://www.madeupwebsite.com/state={"application":"SOMETHING","email":"[email protected]","subdomain":"YES"}

I tried decodeURI like this:

const str = 'https://www.madeupwebsite.com/state={"application":"SOMETHING","email":"[email protected]","subdomain":"YES"}';
const result = decodeURI(str);

but console.log returns this:

"https://www.madeupwebsite.com/state={\"application\":\"SOMETHING\",\"email\":\"[email protected]\",\"subdomain\":\"YES\"}"

Is there a better way to get the email? Do I have to use regex?

CodePudding user response:

A crude first cut at extracting the email address would be:

JSON.parse(decodeURIComponent(str.substring(str.indexOf('state=') 6))).email

This yields:

[email protected]

You have to be more sophisticated, of course, if there are possible multiple parameters besides state in the URL, if you want to do error checking, etc.

CodePudding user response:

Here the solution I came up with:

const decodedUrlObj = decodeURI(str).split("state=").pop();
const formatToJSON = JSON.parse(decodedUrlObj);
console.log("formatToJSON2: ", formatToJSON.username);
// "formatToJSON2: [email protected]
  • Related