How do I get query string value from script path?

Posted by TruMan1 on Stack Overflow See other posts from Stack Overflow or by TruMan1
Published on 2011-01-17T18:41:02Z Indexed on 2011/01/17 18:53 UTC
Read the original article Hit count: 225

Filed under:
|

I am adding my Javsacript file in pages with different query strings in the script path like this:

Page1:

<script type="text/javascript" src="file.js?abc=123"></script>

Page2:

<script type="text/javascript" src="file.js?abc=456"></script>

Page3:

<script type="text/javascript" src="file.js?abc=789"></script>

In my Javascript file, how can I get the value of the "abc" param? I tried using window.location for this, but that does not work.

In case it helps, below is a function I use to find the value of a query string param:

function getQuerystring(key, defaultValue) {
    if (defaultValue == null) defaultValue = "";
    key = key.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
    var regex = new RegExp("[\\?&]" + key + "=([^&#]*)");
    var qs = regex.exec(window.location.href);
    if (qs == null)
        return defaultValue;
    else
        return qs[1];
}

© Stack Overflow or respective owner

Related posts about JavaScript

Related posts about html