Search code examples
javascripturlparametersprototypejs

get URL Parameters from current URL using Prototype JavaScript


I'm noob to JavaScript and want to use Prototype JS Framework to get some URL parameters. Imagine I have the following URL on my current browser:

http://www.somewhere.com?param=abc

how can I get the value of 'param' using any function or utility of Prototype JS ?


Solution

  • You really don't need Prototype for this:

    function get_param(param) {
       var search = window.location.search.substring(1);
       var compareKeyValuePair = function(pair) {
          var key_value = pair.split('=');
          var decodedKey = decodeURIComponent(key_value[0]);
          var decodedValue = decodeURIComponent(key_value[1]);
          if(decodedKey == param) return decodedValue;
          return null;
       };
    
       var comparisonResult = null;
    
       if(search.indexOf('&') > -1) {
          var params = search.split('&');
          for(var i = 0; i < params.length; i++) {
             comparisonResult = compareKeyValuePair(params[i]); 
             if(comparisonResult !== null) {
                break;
             }
          }
       } else {
          comparisonResult = compareKeyValuePair(search);
       }
    
       return comparisonResult;
    }
    
    var param_value = get_param('param'); //abc