I have the following url of my html page, and I am looking for a way to get the value "1997" passed into a string using javascript.
I am thinking of using Regex, but isn't there a much simpler way?
http://localhost:8080/App/sample?proj=1997
I have the following url of my html page, and I am looking for a way to get the value "1997" passed into a string using javascript.
I am thinking of using Regex, but isn't there a much simpler way?
http://localhost:8080/App/sample?proj=1997
Here is a quick function using split
and a for
loop.
function getParam (url, param) {
try {
/* Get the parameters. */
var params = url.split("?")[1].split("&");
/* Iterate over each parameter. */
for (var i = 0, l = params.length; i < l; i++) {
/* Split the string to a key-value pair */
var pair = params[i].split("=");
/* Check whether the param given matches the one iterated. */
if (pair[0] == param) return pair[1];
}
} catch (e) {}
/* Return null, if there is no match. */
return null;
}
/* Example. */
console.log(
getParam("http://localhost/dir/file", "proj"),
getParam("http://localhost:8080/App/sample?proj=1997", "proj")
);