0

How do I get the access_token variable in my URL using javascript .match()?

http://www.facebook.com/connect/login_success.html#access_token=pYBACn8NQeCAVWgiaFG4ZD&expires_in=0

Thanks a lot for your help!

asked May 27, 2012 at 6:06
3
  • you must get it with javascript.match() or your open to other Suggestions? Commented May 27, 2012 at 6:09
  • Sorry for the confusion, I'm definitely open to suggestions. The .match() was just a suggestions Commented May 27, 2012 at 6:14
  • i am working on it :-) you need all this part am i right? pYBACn8NQeCAVWgiaFG4ZD&expires_in=0 or without the =0? Commented May 27, 2012 at 6:18

3 Answers 3

2
var url = 'http://www.facebook.com/connect/login_success.html#access_token=pYBACn8NQeCAVWgiaFG4ZD&expires_in=0';
var token = url.split("#")[1].match(/access_token=([^&]+)/)[1];
answered May 27, 2012 at 6:12

Comments

1

The same as Parth's solution, but without split and a tiny bit more strict:

var url = 'http://www.facebook.com/connect/login_success.html#access_token=pYBACn8NQeCAVWgiaFG4ZD&expires_in=0';
var token = url.match(/(?:#|#.+&)access_token=([^&]+)/)[1];
answered May 27, 2012 at 10:06

3 Comments

Out of curiosity, what exactly does this fragment of the expression suggest "(?:#|#.+&)"
@Karl this is a non-capturing group and means either '#' or '#something&'. I included it to match either '#access_token=' or "#a=b&c=d&access_token=", but not '&other_access_token='
That's clever. Thanks for explaining it to me. I don't want to just blindly use snippets without fully understanding them beforehand.
1

Same as Eugene's but does not throw exception should the match fail

var url = 'http://www.facebook.com/connect/login_success.html#access_token=pYBACn8NQeCAVWgiaFG4ZD&expires_in=0';
var token = (url.match(/(?:#|#.+&)access_token=([^&]+)/) || ['', null])[1];

Returns null if the token is not present in the URL

answered May 27, 2012 at 10:21

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.