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
-
you must get it with javascript.match() or your open to other Suggestions?Blanktext– Blanktext2012年05月27日 06:09:42 +00:00Commented May 27, 2012 at 6:09
-
Sorry for the confusion, I'm definitely open to suggestions. The .match() was just a suggestionsKarl– Karl2012年05月27日 06:14:29 +00:00Commented 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?Blanktext– Blanktext2012年05月27日 06:18:59 +00:00Commented May 27, 2012 at 6:18
3 Answers 3
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
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
Karl
Out of curiosity, what exactly does this fragment of the expression suggest "(?:#|#.+&)"
Eugene Ryabtsev
@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='
Karl
That's clever. Thanks for explaining it to me. I don't want to just blindly use snippets without fully understanding them beforehand.
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
lang-js