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 ?

3

4 Answers 4

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 :)

Sign up to request clarification or add additional context in comments.

Comments

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");

4 Comments

I get "null" for c
It's not gonna give you the value @shahryar ab
But Yes this works if you add var c = url.searchParams.get(c); as per this
it's not a query string, it's anchor text.
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"

Comments

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");

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.