简体   繁体   English

如何从javascript正则表达式中获取此URL的数字

[英]How to get a number out of this url in javascript regex

I have this url 我有这个网址

http://nikerunning.nike.com/nikeplus/v2/services/app/run_list.jsp?userID=1413795052&startIndex=0&endIndex=-1&filterBy=all

I want to fetch 1413795052 number using regex in javascript, how can I achieve this? 我想在javascript中使用正则表达式获取1413795052号码,我该怎么做到这一点?

var url = 'http://nikerunning.nike.com/nikeplus/v2/services/app/run_list.jsp?userID=1413795052&startIndex=0&endIndex=-1&filterBy=all';
var match = url.match(/userID=(\d+)/)
if (match) {
    var userID = match[1];
}

This matches the value of the userID parameter in the URL. 这与URL中的userID参数的值匹配。

/userID=(\\d+)/ is a regex literal. /userID=(\\d+)/是一个正则表达式文字。 How it works: 这个怎么运作:

  • The / are the delimiters, like " for strings /是分隔符,例如" for strings”
  • userID= searches for the string userID= in url userID= userID=url搜索字符串userID=
  • (\\d+) searches for one or more decimal digits and captures it (returns it) (\\d+)搜索一个或多个十进制数字并捕获它(返回)

try it right here in stackoverflow: 在stackoverflow中尝试一下:

window.location.pathname.match(/questions\/(\d+)/)[1]
> "7331140"

or as an integer: 或者作为整数:

~~window.location.pathname.match(/questions\/(\d+)/)[1]
> 7331140

Try with: 试试:

var input = "http://nikerunning.nike.com/nikeplus/v2/services/app/run_list.jsp?userID=1413795052&startIndex=0&endIndex=-1&filterBy=all";

var id = parseInt( input.match(/userID=(\d+)/)[1] );

这将获取查询字符串中的所有数字:

window.location.search.match(/[0-9]+/);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM