使用Javascript正则表达式,如何获取某些短语之间的值..?

时间:2022-11-27 19:04:35

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?

在我的网址中,我想要获得令牌号码,但令牌号码可能是数字或Alpha。我需要始终在不同的场景中获取令牌。如何使用正则表达式实现这一目标?

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?

如何始终从这些URL获取令牌?

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

&token = xyzbacsfhsaof - 在这种情况下“xyzbacsfhsaof”..就像这样

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 个解决方案

#1


4  

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.

请注意,除非您希望捕获多个标记,否则不需要全局修饰符(g)。

#2


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

如果存在正斜杠,它将捕获字母,数字和下划线

#1


4  

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.

请注意,除非您希望捕获多个标记,否则不需要全局修饰符(g)。

#2


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

如果存在正斜杠,它将捕获字母,数字和下划线