March 26, 2012
obtaining querystring from current url in javascript?
Question by AbdulAziz
I have a example URL: http://localhost/PMApp/temp.htm?ProjectID=462 And i have to get the details after the “?” sign that is “ProjectID=462”. I want to do it in JavaScript.
I done this so far and not getting idea what to do next:
var url = window.location.toString();
url.match(?);
Can some body help.Thanks
Answer by Christofer Eliasson
Have a look at the MDN article about window.location
.
The QueryString is available in window.location.search
.
MDN also provide an example of how to the get value of a single key available in window.location.search
.
Something like this:
function loadPageVar (sVar) {
return unescape(window.location.search.replace(new RegExp("^(?:.*[&\?]" + escape(sVar).replace(/[.+*]/g, "\$&") + "(?:\=([^&]*))?)?.*$", "i"), "$1"));
}
// Would alert the value of QueryString-variable called name
alert(loadPageVar("name"));
Answer by Starx
Use window.location.search
to get everything after ?
including ?
Example:
var url = window.location.search;
url = url.replace("?", ''); // remove the ?
alert(url); //alerts ProjectID=462 is your case