the url: http://site/page?object_id=2 I want the number (id).
4 Answers
If you have the URL in a string:
var str = "http://site/page?other_object_id=10&object_id=2";
var match = str.match(/[?&]object_id=(\d+)/);
if (match) {
alert(match[1]); // 2
}
If it's the URL of the current page:
var match = location.search.match(/[?&]object_id=(\d+)/);
if (match) {
alert(match[1]);
}
1 Comment
SLaks
Unless the path contains an
&.Try this:
var url = 'http://site/page?object_id=2';
var object_id = url.match(/object_id=(\d+)/)[1];
1 Comment
Nicole
I would just take the $ away, your \d+ should work fine. Also put the + inside the parentheses -
(\d+).
Locationobject such aswindow.locationor any of theaelement nodes, you can useobj.searchto get the query string without having to use dodgy regexes that will fail if the URL is in an unexpected form. You should also consider using a proper query string parser that breaks on both&and the alternative;and doesdecodeURIComponenton the name and value, if the URL can be in any form.