我见过很多jQuery示例,其中参数大小和名称都是未知的。

我的URL只会有一个字符串

http://example.com?sent=yes

我只想检测:

sent存在吗? 它等于"是"吗?


当前回答

使用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)

其他回答

使用这个

$.urlParam = function(name) {
  var results = new RegExp('[\?&]' + name + '=([^&#]*)').exec(window.location.href);
  return results[1] || 0;
}

我用了这个,很管用。 http://codesheet.org/codesheet/NF246Tzs

function getUrlVars() {
    var vars = {};
    var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
    vars[key] = value;
    });
return vars;
}


var first = getUrlVars()["id"];

这可能有点过分了,但是现在有一个非常流行的用于解析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&param2 = 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

Sameer回答的咖啡脚本版本

getUrlParameter = (sParam) ->
  sPageURL = window.location.search.substring(1)
  sURLVariables = sPageURL.split('&')
  i = 0
  while i < sURLVariables.length
    sParameterName = sURLVariables[i].split('=')
    if sParameterName[0] == sParam
      return sParameterName[1]
    i++