Using Javascript regex, how to get the value between some phrase ..?

In my url, I intend to get the token number, but the token number can be Numeric or Alpha. I need to get the token always in a different scenario. How to achieve this with regular expressions?

Sample URLs:

?&token=1905477219/someother/stuff &token=1905477219 &token=xyzbacsfhsaof &token=xyzbacsfhsaof/some/other 

How can I always get token from these urls?

I tried this:

 /(token=.*)/g 

I'm looking for:

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

and

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

But it does not work. Can anyone help me out?

Thanks everyone, this works great for me:

 var reg = window.location.href.match(/token=([^\/]*)/)[1]; 
+4
source share
2 answers

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

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

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

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

Note that if you do not want to capture multiple tokens, the global modifier ( g ) is not needed.

+4
source
 /token=(\w*)/g 

without 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 when stopped on a slash, if present

+1
source

Source: https://habr.com/ru/post/1491784/


All Articles