简体   繁体   中英

Extracting parameters from JavaScript include tag using a Regex

I am currently trying to parse parameters from a path to a JavaScript file (inside a script tag). At the moment I know which parameters I expect to be there but instead of looking for the expected params I would rather like to just extract all params given.

Example of the script tag which includes a JavaScript file:

<script type="text/javascript" src="https://url/widget.js?param1=A&param2=bb></script>

At the moment I'm just doing this (seperately for each parameter):

jQuery('script').each(function() {
    var script = this;
    if (!script.src) {
        return;
    }    
    var matchKey = script.match(/https\:\/\/url\/widget\.js\?param1=([A-Z]+)/);
    if (matchKey) {
        oSettings.param1 = matchKey[1];
    }
}

So what I need is a regex that extracts both the name of the parameter and the value from the included sript.

Thanks for the assistance!

This tested function works:

function parse_query_vars(text)
{ // Extract name=value pairs from URL query string.
    // Empty object to store name, value pairs.
    var qvars = {},
    // Capture non-empty query string in $1.
        re_q = /\?([^#]+)/, // From '?' up to '#' or EOS.
    // Capture variable name in $1 and value in $2.
        re_nv = /([^=]+)=([^&]*)(?:&(amp;)?|$)/gi,
    // Match array for query string and va=val pairs.
        m =  text.match(re_q),
    // Query string plucked from URL
        q = '';
    // If there is a query string, copy to q var.
    if (m) q = m[1];
    while (m = re_nv.exec(q)) {
        qvars[m[1]] = m[2];
    }
    return qvars; // Return results in object
}

It first extracts any query string from the URL, then iteratively parses out name=value pairs and returns the results in an object. It handles name value pairs separated by either & or &amp; and works if the URL has a #fragment following the query.

Use something like this , or this , or this .

They're not all regex solutions, but then you don't necessarily need a regex. That was a detail that could probably have been left out of the question.

Hope that helps.

(This isn't actually tested)

var scripts = document.getElementsByTagName("script"), i = scripts.length;
var reMatch = /https\:\/\/url\/widget\.js/, path;
// find the correct script
do {
    path = scripts[i--].src;
}
while (!reMatch.test(path));

var map = {}, pairs = path.substring(path.indexOf("?") + 1).split("&"), atoms;
i = pairs.length;
// extract the name-value pairs
while (i--) {
    atoms = pairs[i].split("=");
    map[decodeURIComponent(atoms[0])] = decodeURIComponent(atoms[1]);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM