4

In my url, i'm suppose to get the token number, but the token number may be Numeric or Alpha. I need to get the token always in different scenario. How do I achieve that using Regular Expressions?

Sample URLs:

?&token=1905477219/someother/stuff

&token=1905477219

&token=xyzbacsfhsaof

&token=xyzbacsfhsaof/some/other

How can I always get the token from these kind of URLs?

I tried this:

/(token=.*)/g

I am looking for :

?&token=1905477219/someother/stuff - in this case "1905477219"

and

&token=xyzbacsfhsaof - in this case "xyzbacsfhsaof" .. like so

But it's not working. Can any one can help me?

Thanks all, this is working fine for me:

var reg = window.location.href.match(/token=([^\/]*)/)[1];

2 Answers 2

3

You can use this pattern to match any token with a Latin letter or decimal digit:

/token=([a-z0-9]*)/

Or this which will allow the token to contain any character other than /:

/token=([^\/]*)/

Note that unless you expect to capture multiple tokens, the global modifier (g) is not necessary.

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

4 Comments

@3gwebtrain You just have to change where you put the parenthesis; see my updated answer.
I tested, still i am getting like this: "token=1905477219" - instead "1905477219"
@3gwebtrain How are you getting that value? /token=([a-z0-9]*)/.exec("token=1905477219")[1] will result in "1905477219".
it works fine to me: window.location.href.match(/token=([^\/]*)/)[1];
1
/token=(\w*)/g

without the token

/token=(\w*)/.exec("token=1905477219")[1]
/token=(\w*)/.exec("token=1905477219/somestuff")[1]
/token=(\w*)/.exec("somestuf/token=1905477219")[1]
/token=(\w*)/.exec("somestuf/token=1905477219/somestuff")[1]

// all will return 1905477219

this will capture letters, numbers and underscores while stopping at the forward slash if present

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.