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

Viewed 28

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

https://www.madeupwebsite.com/state=%7B%22application%22:%22SOMETHING%22,%22email%22:%22SOMETHING@madeup.com%22,%22subdomain%22:%22YES%22%7D

I tried decodeURI like this:

const str = 'https://www.madeupwebsite.com/state=%7B%22application%22:%22SOMETHING%22,%22email%22:%22SOMETHING@madeup.com%22,%22subdomain%22:%22YES%22%7D';
const result = decodeURI(str);

but console.log returns this:

"https://www.madeupwebsite.com/state={\"application\":\"SOMETHING\",\"email\":\"SOMETHING@madeup.com\",\"subdomain\":\"YES\"}"

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

2 Answers

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

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

This yields:

SOMETHING@madeup.com

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.

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: SOMETHING@madeup.com
Related