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

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!