-1

Is there a jquery function I can call to retrieve url paramaters.

I have been using this function below and it works fine but it breaks when the url has no parameters. I want it to return '' when there

    function getUrlParameter(name)
     {
   var results = new RegExp('[\\?&]' + name + '=([^&#]*)').exec(window.location.href);
 return results[1] || 0;

      }

So for www.mywebsite.com/index?var1=foo calling getUrlParameter(var1) should return foo and for www.mywebsite.com getUrlParameter(var1) should return ' '

Kwaasi Djin
  • 125
  • 1
  • 11

1 Answers1

-1

To implement this, I have created a function which returns value of any parameters variable.

function GetURLParameter(sParam) { var sPageURL = window.location.search.substring(1); var sURLVariables = sPageURL.split('&'); for (var i = 0; i < sURLVariables.length; i++) { var sParameterName = sURLVariables[i].split('='); if (sParameterName[0] == sParam) { return sParameterName[1]; } } }​

And this is how you can use this function assuming the URL is, "http://dummy.com/?technology=jquery&blog=jquerybyexample".

var tech = GetURLParameter('technology'); var blog = GetURLParameter('blog');

So in above code variable "tech" will have "jQuery" as value and "blog" variable's will be "jquerybyexample".

Prajan Karmacharya
  • 373
  • 1
  • 4
  • 13
  • I want it to work for urls with no variable so if I call getUrlParameter('blog') would return '' for www.mywebsite.com – Kwaasi Djin Apr 04 '14 at 05:54