[英]I need to match a certain part of url path using Regex and Javascript
I have the following link: 我有以下链接:
sitename.com/Default.aspx?PageID=13078494 sitename.com/Default.aspx?PageID=13078494
I want to grab the following: "PageID=13078494". 我想获取以下内容:“ PageID = 13078494”。 This is what I have so far: 这是我到目前为止的内容:
var url = "sitename.com/Default.aspx?PageID=13078494";
urlmatch = url.match([PageID=13078494]);
urlmatch[0];
Is this the proper expression for what I'm trying to do? 这是我想要做的正确表达吗?
Your regex and its syntax are wrong. 您的正则表达式及其语法错误。
A better way would be to not use a regex at all. 更好的方法是根本不使用正则表达式。 Use .split()
instead: 使用.split()
代替:
var urlmatch = url.split('?')[1];
Here's the fiddle: http://jsfiddle.net/qpXNU/ 这是小提琴: http : //jsfiddle.net/qpXNU/
var myregexp = /[?&]PageID=(\d+)/i;
var match = myregexp.exec(url);
if (match != null) {
//This is if your match it successful
result = match[1];
} else {
//This is if url doesn't match
result = "";
}
This one will work regardless of where PageID is. 无论PageID在哪里,都可以使用该代码。 It will match 会匹配
Importantly, it WON'T match 重要的是,它不会匹配
Or without the checking, simply url.match(/[?&]PageID=(\\d+)/i)[1]
, but I'd advice against that unless your SURE it will always match. 或不进行检查,只需url.match(/[?&]PageID=(\\d+)/i)[1]
,但我建议您这样做,除非您确定它总是匹配的。
Try the following regex, which will extract the PageID and place it in the first match group: 尝试以下正则表达式,它将提取PageID并将其放置在第一个匹配组中:
var url = "sitename.com/Default.aspx?PageID=13078494";
urlmatch = url.match(/PageID=(\d+)/);
alert(urlmatch[1]); // 13078494
If you are matching specific value, then it's fine, otherwise use below to match any number of digits in pageID: 如果您要匹配特定的值,那很好,否则请在下面使用它来匹配pageID中的任意数字:
/PageID=\d+/
as: 如:
var url = "sitename.com/Default.aspx?PageID=13078494";
var urlmatch = url.match(/PageID=\d+/);
alert(urlmatch[0]);
or to match 8 exact digits in pageID, use: 或要匹配pageID中的8个精确数字,请使用:
/PageID=\d{8}/
as: 如:
var url = "sitename.com/Default.aspx?PageID=13078494";
var urlmatch = url.match(/PageID=\d{8}/);
alert(urlmatch[0]);
When it comes to handling URLs, the browser is pretty good. 在处理URL方面,浏览器非常出色。
You should convert your string to an actual URL like so: 您应该将字符串转换为实际的URL,如下所示:
var toURL = function (href) {
var a = document.createElement('a');
a.href = href;
return a;
};
Now use the browser's built-in parsing capabilities : 现在使用浏览器的内置解析功能 :
var url = toURL('sitename.com/Default.aspx?PageID=13078494');
alert(url.search);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.