我目前正在尝试将路径中的参数解析为JavaScript文件(在脚本标记内)。目前我知道我希望在那里有哪些参数,但我不想寻找预期的参数,而是想提取给定的所有参数。
包含JavaScript文件的脚本标记示例:
<script type="text/javascript" src="https://url/widget.js?param1=A¶m2=bb></script>
目前我正在这样做(单独为每个参数):
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];
}
}
所以我需要的是一个正则表达式,它提取参数的名称和包含的sript中的值。
感谢您的帮助!
答案 0 :(得分:2)
此测试功能有效:
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
}
它首先从URL中提取任何查询字符串,然后迭代地解析出name = value对并在对象中返回结果。它处理由&
或&
分隔的名称值对,如果网址在查询后面有#fragment
,则会起作用。
答案 1 :(得分:1)
答案 2 :(得分:0)
(这实际上没有经过测试)
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]);
}