I Need To Match A Certain Part Of Url Path Using Regex And Javascript
Solution 1:
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/
Solution 2:
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.
Solution 3:
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
Solution 4:
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]);
Solution 5:
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);
Post a Comment for "I Need To Match A Certain Part Of Url Path Using Regex And Javascript"