I have the following URL, and I want to get the "id" value from it using JavaScript.
https://www.blabla.com/ebookedit?id=B0077RQGX4&commit=Go
I started with this code:
var url = document.URL;
var id_check = /^\id...\E; // NOT SURE HERE
var final_id = new RegExp(id_check,url);
I want to extract the id "B0077RQGX4" and save it into a variable that I would later modify. How would I do it and which functions would I use in JavaScript?
I came up with this:
var final_id;
var url = document.URL;
var id_check = /[?&]id=([^&]+)/i;
var match = id_check.exec(url);
if (match != null) {
final_id = match[1];
} else {
final_id = "";
}
Works for:
https://www.blabla.com/ebookedit?id=B0077RQGX4&commit=Go
final_id = 'B0077RQGX4'
https://www.blabla.com/ebookedit?SomethingElse=Something&id=B0077RQGX4&commit=Go
final_id = 'B0077RQGX4'
https://www.blabla.com/ebookedit?commit=go&id=B0077RQGX4
final_id = 'B0077RQGX4'
https://www.blabla.com/ebookedit?commit=Go
final_id = ''
https://www.blabla.com/ebookedit?id=1234&Something=1&id=B0077RQGX4&commit=Go
final_id = '1234'
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With