简体   繁体   中英

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

I want to grab the following: "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:

var urlmatch = url.split('?')[1];

Here's the fiddle: 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. It will match

  • sitename.com/Default.aspx?PageID=13078494
  • anything.org/Default.aspx?PageID=13078494
  • sitename.com/Default.aspx?foo=bar&PageID=13078494
  • sitename.com/Default.html?foo=bar&PageID=13078494&bar=foo
  • Default.html?foo=bar&PageID=13078494&bar=foo

Importantly, it WON'T match

  • sitename.com/Default.aspx?NotThePageID=13078494

Or without the checking, simply url.match(/[?&]PageID=(\\d+)/i)[1] , but I'd advice against that unless your SURE it will always match.

Try the following regex, which will extract the PageID and place it in the first match group:

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=\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=\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.

You should convert your string to an actual URL like so:

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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