1

I have this URL : http://localhost:3000/#access_token=90kzif5gr8plhtl9286sc1z1qbgoj3&scope=moderation%3Aread&token_type=bearer

and I want to get from this only the access_token value 90kzif5gr8plhtl9286sc1z1qbgoj3

How can I do it in Javascript please ?

VersifiXion
  • 2,152
  • 5
  • 22
  • 40

4 Answers4

1

As you can see in this the simplest way is :

var url_string = "http://localhost:3000/#access_token=90kzif5gr8plhtl9286sc1z1qbgoj3&scope=moderation%3Aread&token_type=bearer"; 
var url = new URL(url_string);
var c = url.searchParams.get("access_token");
shahryar ab
  • 71
  • 1
  • 2
  • 7
1

You can try this by splitting the URL string into three strings and using the access token directly then

var url=http://localhost:3000/#access_token=90kzif5gr8plhtl9286sc1z1qbgoj3&scope=moderation%3Aread&token_type=bearer
var firstHalf=url.split('#access_token=')[1];
var required_token=firstHalf.split("&scope")[0];

print the value of required_token.

Required result will be "90kzif5gr8plhtl9286sc1z1qbgoj3"

champion-runner
  • 1,489
  • 1
  • 13
  • 26
1

your text is the string contained in window.location.hash, and a string of that format can be easily turned into a properly decoded key/value store using the URLSearchParams constructor:

const token = new URLSearchParams(window.location.hash).get("access_token");
Dan O
  • 6,022
  • 2
  • 32
  • 50
1

Here is the solution:

const url = "http://localhost:3000/#access_token=90kzif5gr8plhtl9286sc1z1qbgoj3&scope=moderation%3Aread&token_type=bearer";
const hash = url.substring(url.indexOf('#') + 1);
let result = hash.split('&')
result = result[0].split('=')

console.log(result[1]); // "90kzif5gr8plhtl9286sc1z1qbgoj3"

Happy coding :)

Rashed Rahat
  • 2,357
  • 2
  • 18
  • 38