Home > Blockchain >  Extracting certain values from a large URL string in javascript?
Extracting certain values from a large URL string in javascript?

Time:07-16

I have a big URL hash that is given in string form and need to extract each part of it:

type=recovery&access_token=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9eyJhdWQiOiJhdXRoZW50aWNhdGV&expires_in=3600&refresh_token=sYlurmTtfrAhyHl39Oqwww&token_type=bearer&type=recovery

I have tried substr() but it isn't reliable because each item may have a differing amount of characters each time.

What's the best way to extract type, access_token, expires_in, refresh_token, token_type reliably?

CodePudding user response:

Please use URLSearchParams

var urlSearchParams = new URLSearchParams("type=recovery&access_token=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9eyJhdWQiOiJhdXRoZW50aWNhdGV&expires_in=3600&refresh_token=sYlurmTtfrAhyHl39Oqwww&token_type=bearer&type=recovery")

const params = Object.fromEntries(urlSearchParams.entries());

console.log(params)

CodePudding user response:

You could use URL:

// Adding a dummy domain so the string is a valid url
let x = new URL('http://dummydomain.tpl/dummyfile.ext?'   
'type=recovery&access_token=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9eyJhdWQiOiJhdXRoZW50aWNhdGV&expires_in=3600&refresh_token=sYlurmTtfrAhyHl39Oqwww&token_type=bearer&type=recovery');

x.searchParams.get("refresh_token")
  • Related