我见过很多jQuery示例,其中参数大小和名称都是未知的。
我的URL只会有一个字符串
http://example.com?sent=yes
我只想检测:
sent存在吗? 它等于"是"吗?
我见过很多jQuery示例,其中参数大小和名称都是未知的。
我的URL只会有一个字符串
http://example.com?sent=yes
我只想检测:
sent存在吗? 它等于"是"吗?
当前回答
也许你应该给JS牙医看看?(免责声明:代码是我写的)
代码:
document.URL == "http://helloworld.com/quotes?id=1337&author=kelvin&message=hello"
var currentURL = document.URL;
var params = currentURL.extract();
console.log(params.id); // 1337
console.log(params.author) // "kelvin"
console.log(params.message) // "hello"
使用牙医JS,你基本上可以在所有字符串上调用extract()函数(例如,document.URL.extract()),你会得到所有找到的参数的HashMap。它还可以自定义处理分隔符等。
缩小版< 1kb
其他回答
最好的解决方案。
var getUrlParameter = function getUrlParameter(sParam) {
var sPageURL = window.location.search.substring(1),
sURLVariables = sPageURL.split('&'),
sParameterName,
i;
for (i = 0; i < sURLVariables.length; i++) {
sParameterName = sURLVariables[i].split('=');
if (sParameterName[0] === sParam) {
return sParameterName[1] === undefined ? true : decodeURIComponent(sParameterName[1]);
}
}
return false;
};
这就是你如何使用这个函数假设URL是, http://dummy.com/?technology=jquery&blog=jquerybyexample。
var tech = getUrlParameter('technology');
var blog = getUrlParameter('blog');
试试这个工作演示http://jsfiddle.net/xy7cX/
火:
inArray: http://api.jquery.com/jQuery.inArray/
这应该会有帮助:)
code
var url = "http://myurl.com?sent=yes"
var pieces = url.split("?");
alert(pieces[1] + " ===== " + $.inArray("sent=yes", pieces));
还有一个使用URI.js库的例子。
例子准确地回答了所问的问题。
var url = 'http://example.com?sent=yes'; var urlParams = new URI(url).search(true); // 1. Does sent exist? var sendExists = urlParams.sent !== undefined; // 2. Is it equal to "yes"? var sendIsEqualtToYes = urlParams.sent == 'yes'; // output results in readable form // not required for production if (sendExists) { console.log('Url has "sent" param, its value is "' + urlParams.sent + '"'); if (urlParams.sent == 'yes') { console.log('"Sent" param is equal to "yes"'); } else { console.log('"Sent" param is not equal to "yes"'); } } else { console.log('Url hasn\'t "sent" param'); } <script src="https://cdnjs.cloudflare.com/ajax/libs/URI.js/1.18.2/URI.min.js"></script>
如果有&在URL参数像filename="p&g.html"&uid=66
在这种情况下,第一个函数将不能正常工作。所以我修改了代码
function getUrlParameter(sParam) {
var sURLVariables = window.location.search.substring(1).split('&'), sParameterName, i;
for (i = 0; i < sURLVariables.length; i++) {
sParameterName = sURLVariables[i].split('=');
if (sParameterName[0] === sParam) {
return sParameterName[1] === undefined ? true : decodeURIComponent(sParameterName[1]);
}
}
}
使用URLSearchParams:
var params = new window.URLSearchParams(window.location.search);
console.log(params.get('name'));
注意兼容性(大多数情况下是好的,但IE和Edge,可能是不同的故事,检查这个兼容性参考:https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams)