获取转义的网址参数

Sin*_*hus 301 javascript url url-parameters query-string

我正在寻找一个可以获取URL参数的jQuery插件,并支持此搜索字符串而不输出JavaScript错误:"格式错误的URI序列".如果没有支持这个的jQuery插件,我需要知道如何修改它来支持这个.

?search=%E6%F8%E5
Run Code Online (Sandbox Code Playgroud)

解码后,URL参数的值应为:

æøå
Run Code Online (Sandbox Code Playgroud)

(字符是挪威语).

我无权访问服务器,因此我无法对其进行任何修改.

Jam*_*mes 417

function getURLParameter(name) {
    return decodeURI(
        (RegExp(name + '=' + '(.+?)(&|$)').exec(location.search)||[,null])[1]
    );
}
Run Code Online (Sandbox Code Playgroud)

  • 当未定义参数时,此函数返回'null'而不是null ... js的快乐... (34认同)
  • 使用`name ='bar'`,我认为这个正则表达式匹配''foobar = 10'并返回''10'.也许你可以在正则表达式的开头加上''[?|&]'`.干杯! (33认同)
  • 这很好,但是decodeURIComponent更好,例如我的param中有一个hashcode(%23),decodeURI会忽略它.而且我不会返回null,而是"",因为decodeURI(null)==="null",这是一个奇怪的返回值,""更好; 你可以做if(!getURLParameter("param"))而不是if(getURLParameter("param")==="null").所以,我的改进版本:decodeURIComponent((RegExp(name +'='+'(.+?)(&| $)').exec(location.search)|| [,""])[1]) (25认同)
  • 您可能需要"decodeURIComponent()"而不是"decodeURI()",尤其是当您将返回URL等有趣数据作为URL参数传递时 (12认同)
  • 向下投票,因为无论结果是否被发现都返回字符串,无论你把什么作为替代数组,例如[,null],因为thre结果被包装在decodeURI中,将任何东西变成字符串,Sanjeev是对的但是他的代码没有正确测试,简单的复制和粘贴不起作用.`function getURLParameter(name){var p = RegExp(name +'='+'(.+?)(&| $)').exec(location.search); if(!! p){p = decodeURI(p [1]); } return p; }` (3认同)
  • **这修复'null'而不是null问题:**function getURLParameter(name){var param =(RegExp(name +'='+'(.+?)(&| $)').exec(location.搜索)|| [,空])[1]; return(param?:decodeURI(param):param); }} (2认同)
  • 如果有人试图摆脱这方面的JSLint错误,只需将[,null]更改为[undefined,null] (2认同)

rad*_*and 293

以下是我从这里的评论中创建的内容,以及修复未提及的错误(例如实际返回null,而不是'null'):

function getURLParameter(name) {
    return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.search)||[,""])[1].replace(/\+/g, '%20'))||null;
}
Run Code Online (Sandbox Code Playgroud)

  • 这应该是公认的答案.获得真正的null而不是"null"更好. (18认同)
  • 如果有人需要这个转换为coffeescript:getURLParameter :( name) - > return decodeURIComponent((new RegExp("[?|&]#{name} =([^&;] +?)(&| ## |; | $)").exec(location.search)|| [null,""])[1] .replace(/\+/g,'%20'))|| null; (11认同)
  • 如何在RegExp前添加`new`?减少皮棉警告. (6认同)
  • 当然,它已被添加. (2认同)

Luc*_*cas 107

你真正想要的是jQuery URL Parser插件.使用此插件,获取特定URL参数(对于当前URL)的值如下所示:

$.url().param('foo');
Run Code Online (Sandbox Code Playgroud)

如果你想要一个带参数名称的对象作为键和参数值作为值,你只需要不param()带参数调用,如下所示:

$.url().param();
Run Code Online (Sandbox Code Playgroud)

此库也适用于其他网址,而不仅仅是当前网址:

$.url('http://allmarkedup.com?sky=blue&grass=green').param();
$('#myElement').url().param(); // works with elements that have 'src', 'href' or 'action' attributes
Run Code Online (Sandbox Code Playgroud)

由于这是一个完整的URL解析库,您还可以从URL获取其他信息,如指定的端口,或路径,协议等:

var url = $.url('http://allmarkedup.com/folder/dir/index.html?item=value');
url.attr('protocol'); // returns 'http'
url.attr('path'); // returns '/folder/dir/index.html'
Run Code Online (Sandbox Code Playgroud)

它还有其他功能,请查看其主页以获取更多文档和示例.

而不是写你自己的URI解析器为这一特定目的的还挺作品在大多数情况下,使用一个实际的URI解析器.根据答案,来自其他答案的代码可以返回'null'而不是null,不能使用空参数(?foo=&bar=x),不能一次解析并返回所有参数,如果您反复查询参数的URL等,则重复工作.

使用实际的URI解析器,不要发明自己的.

对于那些厌恶jQuery的人来说,有一个纯JS的插件版本.

  • 问题是"使用jQuery获取URL参数".我的回答回答了这个问题.其他答案指示用户基本上为这个特定用例编写自己的URI解析器,这是一个可怕的想法.解析URI比人们想象的更复杂. (23认同)
  • 这是我正在寻找的答案,并且非常jQuery-ish,与其他一些答案不同. (2认同)

Edw*_*son 43

如果您不知道URL参数是什么,并希望获得具有参数中的键和值的对象,则可以使用以下命令:

function getParameters() {
  var searchString = window.location.search.substring(1),
      params = searchString.split("&"),
      hash = {};

  if (searchString == "") return {};
  for (var i = 0; i < params.length; i++) {
    var val = params[i].split("=");
    hash[unescape(val[0])] = unescape(val[1]);
  }
  return hash;
}
Run Code Online (Sandbox Code Playgroud)

使用类似url调用getParameters()/posts?date=9/10/11&author=nilbus将返回:

{
  date:   '9/10/11',
  author: 'nilbus'
}
Run Code Online (Sandbox Code Playgroud)

我不会在这里包含代码,因为它甚至离问题更远,但weareon.net发布了一个库,它允许操作URL中的参数:


CMS*_*CMS 40

您可以使用浏览器本机location.search属性:

function getParameter(paramName) {
  var searchString = window.location.search.substring(1),
      i, val, params = searchString.split("&");

  for (i=0;i<params.length;i++) {
    val = params[i].split("=");
    if (val[0] == paramName) {
      return unescape(val[1]);
    }
  }
  return null;
}
Run Code Online (Sandbox Code Playgroud)

但是有一些jQuery插件可以帮助你:

  • 我建议使用decodeURIComponent()而不是unescape() (8认同)
  • 这比所有正则表达式的单行程更清晰,更易读(并且可能更无错误). (4认同)

Eug*_*ash 25

基于999的答案:

function getURLParameter(name) {
    return decodeURIComponent(
        (location.search.match(RegExp("[?|&]"+name+'=(.+?)(&|$)'))||[,null])[1]
    );  
}
Run Code Online (Sandbox Code Playgroud)

变化:

  • decodeURI() 被替换为 decodeURIComponent()
  • [?|&] 在正则表达式的开头添加

  • 如果您能解释为何进行这些更改,可能对其他人有帮助.谢谢 (3认同)
  • 不处理空参数:`?a =&b = 1`.更好的正则表达式是:`"[?&]"+ name +"=([^&]*)"` (3认同)

小智 6

需要添加i参数以使其不区分大小写:

  function getURLParameter(name) {
    return decodeURIComponent(
      (RegExp(name + '=' + '(.+?)(&|$)', 'i').exec(location.search) || [, ""])[1]
    );
  }
Run Code Online (Sandbox Code Playgroud)


Sin*_*hus 2

你不应该使用 jQuery 来做这样的事情!
\n现代方法是通过像 Bower 这样的包管理器来使用小型可重用模块。

\n\n

我创建了一个小模块,可以将查询字符串解析为对象。像这样使用它:

\n\n
// parse the query string into an object and get the property\nqueryString.parse(unescape(location.search)).search;\n//=> \xc3\xa6\xc3\xb8\xc3\xa5\n
Run Code Online (Sandbox Code Playgroud)\n