我见过很多jQuery示例,其中参数大小和名称都是未知的。
我的URL只会有一个字符串
http://example.com?sent=yes
我只想检测:
sent存在吗? 它等于"是"吗?
我见过很多jQuery示例,其中参数大小和名称都是未知的。
我的URL只会有一个字符串
http://example.com?sent=yes
我只想检测:
sent存在吗? 它等于"是"吗?
当前回答
var RequestQuerystring; (窗口。Onpopstate = function () { var匹配, pl = /\+/g, //用空格替换加法符号的正则表达式 搜索= /([^&=]+)=?([^&]*)/g, decode =函数(s){返回decodeURIComponent(s)。替换(pl, " "));}, Query = window.location.search.substring(1); RequestQuerystring = {}; While (match = search.exec(查询)) RequestQuerystring[decode(match[1])] = decode(match[2]); })();
RequestQuerystring现在是一个包含所有参数的对象
其他回答
从字符串中获取参数:
Object.defineProperty(String.prototype, 'urlParam', {
value: function (param) {
"use strict";
var str = this.trim();
var regex = "[\?&]" + param + "=([^&#]*)";
var results = new RegExp(regex, "i").exec(str);
return (results !== null) ? results[1] : '';
}
});
使用方法:
var src = 'http://your-url.com/?param=value'
console.log(src.urlParam(param)); // returns 'value'
函数GetRequestParam(参数) { Var res = null; 尝试{ var qs = decodeURIComponent(window.location.search.substring(1));//获取then之后的所有内容'?URI中的' Var ar = q .split('&'); 美元。Each (ar, function(a, b){ Var kv = b.split('='); If (param === kv[0]){ Res = kv[1]; 返回false;//打破循环 } }); }捕捉(e) {} 返回res; }
2023年起的解决方案
我们有:http://example.com?sent=yes
let searchParams = new URLSearchParams(window.location.search)
sent存在吗?
searchParams.has('sent') // true
它等于"是"吗?
let param = searchParams.get('sent')
然后比较一下。
这可能有点过分了,但是现在有一个非常流行的用于解析uri的库,叫做URI.js。
例子
var uri = "http://example.org/foo.html?technology=jquery&technology=css&blog=stackoverflow"; var components = URI.parse(uri); var query = URI.parseQuery(components['query']); document.getElementById("result").innerHTML = "URI = " + uri; document.getElementById("result").innerHTML += "<br>technology = " + query['technology']; // If you look in your console, you will see that this library generates a JS array for multi-valued queries! console.log(query['technology']); console.log(query['blog']); <script src="https://cdnjs.cloudflare.com/ajax/libs/URI.js/1.17.0/URI.min.js"></script> <span id="result"></span>
jQuery代码片段,以获取动态变量存储在url作为参数,并将它们存储为JavaScript变量,以供您的脚本使用:
$.urlParam = function(name){
var results = new RegExp('[\?&]' + name + '=([^&#]*)').exec(window.location.href);
if (results==null) {
return null;
}
return decodeURI(results[1]) || 0;
}
example.com ? param1 = name¶m2 = id = 6
$.urlParam('param1'); // name
$.urlParam('id'); // 6
$.urlParam('param2'); // null
带有空格的参数示例
http://www.jquery4u.com?city=Gold Coast
console.log($.urlParam('city'));
//output: Gold%20Coast
console.log(decodeURIComponent($.urlParam('city')));
//output: Gold Coast