1

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?

5 Answers 5

2

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")));
Sign up to request clarification or add additional context in comments.

3 Comments

really change getParameterByName("count", $("script[src*='test.js']").attr("src") that instead $("script[src*='test.js'] was use name js file where execute script? for example if script execute in file test.js than use name this file(test.js) and if script execute in file test2.js than automatically use name this file(test2.js) ?
@LeoLoki,you mean,can we detect the name of script file that is running the script and replace it with $("script[src*='test.js']")?
@LeoLoki, I updated the answer that may help you to detect the current script
2

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>

1 Comment

it ok if i know name and position key. but how get value from key? i update question. and i would like get key in file test.js
1

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);
});

Comments

0

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]);
});

2 Comments

it ok if i know name and position key. but how get value from key? i update question.
and i would like get key in file test.js
0
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, " "));
}

4 Comments

not work and getParameterByName(count); will be show error, becouse count not exists
@LeoLoki , please use 'count' instead of count. I made a mistake in my previous suggestion.
yes, but not work with window.location.href it will be work if use $("script[src*='test.js']").attr("src") as value parametr url
I suggest to give id to this particular script tag. And then pass the src attribute to the getParameterByName as follows <script src="/js/example/test.js?count=2321" id='testJs'></script> <script> var url = $('#testJs').attr('src'); var paramCount = getParameterByName('count', url); </script>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.