While you can do this with Regex, it's probably going to be easier and/or more consistent if you use a non-Regex approach. This is the case because the query string could have a wide variety of layouts (with the id
value first, last, or in the middle).
EDIT: @AdrianaVillafañe proves that this can be done easily with a Regex! I'm going to leave this JS-only method here because it does work.
I like to use this JavaScript method to parse query string from a URL and get the first value that matches the desired name. In your case, "id" would be the name
parameter.
// parses the query string provided and returns the value
function GetQueryVariable(query, name) {
if (query.indexOf("?") == 0) { query = query.substr(1); }
var pairs = query.split("&");
for (var i = 0; i < pairs.length; i++) {
var pair = pairs[i].split("=");
if (pair[0] == name) {
return pair[1];
}
}
return "";
}
To use this method, you would pass in the query string portion of the URL and the name of the value that you want to get. If you want to parse the URL of the current request, you could do this:
var value = GetQueryVariable(location.search, "id");
Trying to do this in a Regex will most likely be inconsistent at best when trying to handle the possible variations of the query string layout.