Tengo un gran hash de URL que se proporciona en forma de cadena y necesito extraer cada parte:
type=recovery&access_token=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9eyJhdWQiOiJhdXRoZW50aWNhdGV&expires_in=3600&refresh_token=sYlurmTtfrAhyHl39Oqwww&token_type=bearer&type=recoveryProbé substr() pero no es confiable porque cada elemento puede tener una cantidad diferente de caracteres cada vez.
¿Cuál es la mejor manera de extraer type, access_token, expires_in, refresh_token, token_type de manera confiable?
Podrías usar la 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")Utilice 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)