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

我的URL只会有一个字符串

http://example.com?sent=yes

我只想检测:

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


当前回答

函数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; }

其他回答

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++

从字符串中获取参数:

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

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

这里有一个很棒的图书馆: https://github.com/allmarkedup/purl

这能让你做得更简单

url = 'http://example.com?sent=yes';
sent = $.url(url).param('sent');
if (typeof sent != 'undefined') { // sent exists
   if (sent == 'yes') { // sent is equal to yes
     // ...
   }
}

这个例子假设您正在使用jQuery。你也可以使用它只是简单的javascript,语法会有点不同。