Leo Loki
Leo Loki

Reputation: 2575

How get params from url to javascript or jquery file?

For example js file include to page:

<script src="/js/example/test.js?count=2321"></script>

How get value count in javascript file test.js from url /js/example/test.js?count=2321?

P.S.: how get if i do not know position key? i.e. how get value parametr from key?

Upvotes: 1

Views: 443

Answers (5)

hsh
hsh

Reputation: 1855

Define a method like below to fetch all key values from a url:

function getUrlVars(url)
{
   var vars = [], hash;
   if(url == undefined || url.indexOf('?') ==  -1)
     return vars;
   var hashes = url.slice(url.indexOf('?') + 1).split('&');
   for(var i = 0; i < hashes.length; i++)
   {
      hash = hashes[i].split('=');
      vars.push({key : hash[0] , value : hash[1]});
   }
   return vars;
}

this method returns an object array that contains all available Key/Values of the url.

finally you can get the src from any script tag and get all available Key/Values like this:

$("script").each(function(){
  if($(this).attr("src") != undefined){
    console.log($(this).attr("src") + ":");
    console.log(getUrlVars($(this).attr("src")));
  }
});

$(document).ready(function(){
  function getUrlVars(url)
  {
   var vars = [], hash;
    if(url == undefined || url.indexOf('?') ==  -1)
      return vars;
   var hashes = url.slice(url.indexOf('?') + 1).split('&');
   for(var i = 0; i < hashes.length; i++)
   {
      hash = hashes[i].split('=');
      vars.push({key : hash[0] , value : hash[1]});
   }
   return vars;
  }
  $("script").each(function(){
    if($(this).attr("src") != undefined){
      console.log($(this).attr("src") + ":");
      console.log(getUrlVars($(this).attr("src")));
    }
  });
   
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="/js/example/test.js?count=2321&customKey=1233&customKey2=sdffds"></script>
<script src="/js/example/test1.js?count2=2321&Key2=sdffds"></script>
<script src="/js/example/test2.js?count2=2321&key1=1233"></script>

You can also use the following method to get a specific key from any url:

function getParameterByName(name, url) {
   if (!url) url = window.location.href;
   name = name.replace(/[\[\]]/g, "\\$&");
   var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
       results = regex.exec(url);
   if (!results) return null;
   if (!results[2]) return '';
   return decodeURIComponent(results[2].replace(/\+/g, " "));
}

and get the value of a key like this:

getParameterByName("count", $("script[src*='test.js']").attr("src"))

$(document).ready(function(){
  function getParameterByName(name, url) {
    if (!url) url = window.location.href;
    name = name.replace(/[\[\]]/g, "\\$&");
    var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
        results = regex.exec(url);
    if (!results) return null;
    if (!results[2]) return '';
    return decodeURIComponent(results[2].replace(/\+/g, " "));
  }
  
   console.log( getParameterByName("count", $("script[src*='test.js']").attr("src")));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="/js/example/test.js?count=2321"></script>

Edit (Detect current script): There are many ways to detect the current script tag that you can find HERE, but I think the most accurate way is to define a method in each of your scripts with its name on it and loop over all scripts to find the script you want:

function isMe(scriptElem){
   return scriptElem.getAttribute('src') === "Your Current Script Src";
}

var me = null;
var scripts = document.getElementsByTagName("script")
for (var i = 0; i < scripts.length; ++i) {
   if( isMe(scripts[i])){
     me = scripts[i];
   }
}
console.log( getParameterByName("count", $(me).attr("src")));

Upvotes: 2

Vinie
Vinie

Reputation: 2993

Try This

function getParameterByName(name,url) 
{
    name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
    var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
    results = regex.exec(url);
    return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}

$(document).ready(function(){
    var url = $("script[src*='test.js']").attr("src");
    getParameterByName('count',url);
});

Upvotes: 1

Laxman
Laxman

Reputation: 1158

var paramCount = getParameterByName('count');
function getParameterByName(name, url) {
    if (!url) url = window.location.href;
    name = name.replace(/[\[\]]/g, "\\$&");
    var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
        results = regex.exec(url);
    if (!results) return null;
    if (!results[2]) return '';
    return decodeURIComponent(results[2].replace(/\+/g, " "));
}

Upvotes: 0

Alexis
Alexis

Reputation: 5831

Try something like this.

Loop on <script>, search the script that you want and cut at the parameter ?

$(document).ready(function(){
  var parameters = $("script[src*='test.js']").attr("src").split('?')[1].split('&');
  var count="Not found";
  for(var i=0;i<parameters.length;i++)
  {
    var param=parameters[i].split('=');
        if(param[0]=="count")
            count=param[1];
  }

  console.log(count);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="/js/example/test.js?not=2321&over=blabla&one=two&count=1234"></script>

Upvotes: 2

kkakkurt
kkakkurt

Reputation: 2800

You can also do it like this:

Give an id to your script:

<script id="YourId" src="/js/example/test.js?count=2321"></script>

And then:

$(document).ready(function() {
    alert($("#YourId").attr('src').split('=')[1]);
});

Upvotes: 0

Related Questions