本文翻译自:Parse query string in JavaScript [duplicate]

Possible Duplicate: 可能重复:
How can I get query string values? 如何获取查询字符串值?

I need to parse the query string www.mysite.com/default.aspx?dest=aboutus.aspx . 我需要解析查询字符串www.mysite.com/default.aspx?dest=aboutus.aspx How do I get the dest variable in JavaScript? 如何在JavaScript中获取dest变量?


#1楼

参考:https://stackoom.com/question/8lqZ/在JavaScript中解析查询字符串-重复


#2楼

function parseQuery(queryString) {var query = {};var pairs = (queryString[0] === '?' ? queryString.substr(1) : queryString).split('&');for (var i = 0; i < pairs.length; i++) {var pair = pairs[i].split('=');query[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1] || '');}return query;
}

Turns query string like hello=1&another=2 into object {hello: 1, another: 2} . 将查询字符串(如hello=1&another=2转换为对象{hello: 1, another: 2} From there, it's easy to extract the variable you need. 从那里,很容易提取您需要的变量。

That said, it does not deal with array cases such as "hello=1&hello=2&hello=3" . 也就是说,它不处理诸如"hello=1&hello=2&hello=3"数组情况。 To work with this, you must check whether a property of the object you make exists before adding to it, and turn the value of it into an array, pushing any additional bits. 要使用它,您必须在添加之前检查您所创建的对象的属性是否存在,并将其值转换为数组,并推送任何其他位。


#3楼

I wanted to pick up specific links within a DOM element on a page, send those users to a redirect page on a timer and then pass them onto the original clicked URL. 我想拿起一个页面上的DOM元素 特定环节,把那些用户重定向页面上的计时器,然后将它们传递给原始广告点击的网址。 This is how I did it using regular javascript incorporating one of the methods above. 这就是我使用常规javascript结合上述方法之一的方法。

Page with links: Head 带链接的页面: Head

  function replaceLinks() {
var content = document.getElementById('mainContent');var nodes = content.getElementsByTagName('a');for (var i = 0; i < document.getElementsByTagName('a').length; i++) {{href = nodes[i].href;if (href.indexOf("thisurl.com") != -1) {nodes[i].href="http://www.thisurl.com/redirect.aspx" + "?url=" + nodes[i];nodes[i].target="_blank";}}}
}

Body 身体

<body onload="replaceLinks()">

Redirect page Head 重定向页面 头部

   function getQueryVariable(variable) {var query = window.location.search.substring(1);var vars = query.split('&');for (var i = 0; i < vars.length; i++) {var pair = vars[i].split('=');if (decodeURIComponent(pair[0]) == variable) {return decodeURIComponent(pair[1]);}}console.log('Query variable %s not found', variable);}function delayer(){window.location = getQueryVariable('url')}

Body 身体

<body onload="setTimeout('delayer()', 1000)">

#4楼

Following on from my comment to the answer @bobby posted, here is the code I would use: 继我对@bobby发布的答案的评论之后,这里是我将使用的代码:

    function parseQuery(str){if(typeof str != "string" || str.length == 0) return {};var s = str.split("&");var s_length = s.length;var bit, query = {}, first, second;for(var i = 0; i < s_length; i++){bit = s[i].split("=");first = decodeURIComponent(bit[0]);if(first.length == 0) continue;second = decodeURIComponent(bit[1]);if(typeof query[first] == "undefined") query[first] = second;else if(query[first] instanceof Array) query[first].push(second);else query[first] = [query[first], second]; }return query;}

This code takes in the querystring provided (as 'str') and returns an object. 此代码接受提供的查询字符串(作为'str')并返回一个对象。 The string is split on all occurances of &, resulting in an array. 字符串在&的所有出现时被拆分,从而产生一个数组。 the array is then travsersed and each item in it is split by "=". 然后对该数组进行travsers,并将其中的每个项目拆分为“=”。 This results in sub arrays wherein the 0th element is the parameter and the 1st element is the value (or undefined if no = sign). 这导致子数组,其中第0个元素是参数,第1个元素是值(如果没有=符号,则为undefined)。 These are mapped to object properties, so for example the string "hello=1&another=2&something" is turned into: 这些映射到对象属性,因此例如字符串“hello = 1&another = 2&something”变为:

{
hello: "1",
another: "2",
something: undefined
}

In addition, this code notices repeating reoccurances such as "hello=1&hello=2" and converts the result into an array, eg: 此外,此代码注意到重复重复,例如“hello = 1&hello = 2”并将结果转换为数组,例如:

{
hello: ["1", "2"]
}

You'll also notice it deals with cases in whih the = sign is not used. 你还会注意到它处理了没有使用=符号的情况。 It also ignores if there is an equal sign straight after an & symbol. 如果在&符号后面有一个等号,它也会忽略它。

A bit overkill for the original question, but a reusable solution if you ever need to work with querystrings in javascript :) 对于原始问题有点矫枉过正,但如果您需要在javascript中使用查询字符串,则可以使用可重用的解决方案:)


#5楼

I wanted a simple function that took a URL as an input and returned a map of the query params. 我想要一个简单的函数,它将URL作为输入并返回查询参数的映射。 If I were to improve this function, I would support the standard for array data in the URL, and or nested variables. 如果我要改进这个功能,我会支持URL和/或嵌套变量中的数组数据标准。

This should work back and for with the jQuery.param( qparams ) function. 这应该可以使用jQuery.param(qparams)函数。

function getQueryParams(url){var qparams = {},parts = (url||'').split('?'),qparts, qpart,i=0;if(parts.length <= 1 ){return qparams;}else{qparts = parts[1].split('&');for(i in qparts){qpart = qparts[i].split('=');qparams[decodeURIComponent(qpart[0])] = decodeURIComponent(qpart[1] || '');}}return qparams;
};

#6楼

Me too! 我也是! http://jsfiddle.net/drzaus/8EE8k/ http://jsfiddle.net/drzaus/8EE8k/

(Note: without fancy nested or duplicate checking) (注意:没有花哨的嵌套或重复检查)

deparam = function (querystring) {// remove any preceding url and splitquerystring = querystring.substring(querystring.indexOf('?')+1).split('&');var params = {}, pair, d = decodeURIComponent;// march and parsefor (var i = querystring.length - 1; i >= 0; i--) {pair = querystring[i].split('=');params[d(pair[0])] = d(pair[1] || '');}return params;
};//--  fn  deparam

And tests: 并测试:

var tests = {};
tests["simple params"] = "ID=2&first=1&second=b";
tests["full url"] = "http://blah.com/?" + tests["simple params"];
tests['just ?'] = '?' + tests['simple params'];var $output = document.getElementById('output');
function output(msg) {$output.innerHTML += "\n" + Array.prototype.slice.call(arguments, 0).join("\n");
}
$.each(tests, function(msg, test) {var q = deparam(test);// prompt, querystring, result, reverseoutput(msg, test, JSON.stringify(q), $.param(q));output('-------------------');
});

Results in: 结果是:

simple params
ID=2&first=1&second=b
{"second":"b","first":"1","ID":"2"}
second=b&first=1&ID=2
-------------------
full url
http://blah.com/?ID=2&first=1&second=b
{"second":"b","first":"1","ID":"2"}
second=b&first=1&ID=2
-------------------
just ?
?ID=2&first=1&second=b
{"second":"b","first":"1","ID":"2"}
second=b&first=1&ID=2
-------------------

在JavaScript中解析查询字符串[重复]相关推荐

  1. 在JavaScript中解析JSON? [重复]

    本文翻译自:Parse JSON in JavaScript? [duplicate] This question already has answers here : 这个问题已经在这里有了答案 : ...

  2. 取出url中的字符_如何在JavaScript中解析URL:例如主机名,路径名,查询,哈希?...

    统一资源定位符(缩写URL)是对Web资源(网页,图像,文件)的引用.URL指定资源位置和检索资源的机制(http,ftp,mailto). 例如,这是此博客文章的URL: 通常,您需要访问URL的特 ...

  3. 如何在javascript中解析带有两个小数位的浮点数?

    本文翻译自:How to parse float with two decimal places in javascript? I have the following code. 我有以下代码. I ...

  4. JavaScript中常见的字符串操作函数及用法汇总

    转载地址:http://www.jb51.net/article/65358.htm 这篇文章主要介绍了JavaScript中常见的字符串操作函数及用法,实例汇总了javascript常见的字符串转换 ...

  5. Gin 框架学习笔记(01)— 自定义结构体绑定表单、绑定URI、自定义log、自定义中间件、路由组、解析查询字符串、上传文件、使用HTTP方法

    要实现一个 API 服务器,首先要考虑两个方面:API 风格和媒体类型.Go 语言中常用的 API 风格是 RPC 和 REST,常用的媒体类型是 JSON.XML 和 Protobuf.在 Go A ...

  6. JS/JavaScript中解析JSON --- JSON.parse()、JSON.stringify()以及$.parseJSON()使用详解

    JS/JavaScript中解析JSON --- JSON.parse().JSON.stringify()以及$.parseJSON()使用详解 现在JSON格式在web开发中非常重要,特别是在使用 ...

  7. java两字符串是否相等_Java与JavaScript中判断两字符串是否相等的区别

    JavaScript是一种常用的脚本语言,这也决定了其相对于其他编程语言显得并不是很规范.在JavaScript中判断两字符串是否相等 直接用==,这与C++里的String类一样.而Java里的等号 ...

  8. 【Win 10 应用开发】分析 URI 中的查询字符串

    分析URI中的字符有K种方法(K >= 2),如果查询字符串中的参数比较简单,可以通过子字符串查找的方式来处理:如果查询字符串相对复杂,你可以使用正则表达式来匹配 key1=value1 ,  ...

  9. JavaScript中的对象比较[重复]

    本文翻译自:Object comparison in JavaScript [duplicate] This question already has answers here : 这个问题已经在这里 ...

最新文章

  1. 【干货】搭建社区运营团队的一些经验和“血的教训”
  2. String为null
  3. 通过 SAP UI5 的 TypeScript 开发环境,来学习什么是 DefinitelyTyped
  4. 在Application_Error事件中获取当前的Action和Control
  5. HTML5如何控制暂停播放停止
  6. mall-swarm是一套微服务商城系统
  7. linux shell编程if语句内判断参数
  8. [Win] 免登录百度网盘高速下载器 ENFI下载器 v1.3.1
  9. 史上最详细的梯度下降优化算法介绍(从SGD到Adam至Lookahead)
  10. 小米电视机如何重新匹配遥控器
  11. 统计|如何建立单总体方差的置信区间
  12. EditText过滤特殊符号
  13. 10min快速回顾C++语法(六)函数专题
  14. JS——日期的横杠、斜杠相互替换
  15. 极路由无线打印机服务器,极路由Hiwifi最多可连接有几台设备
  16. openEuler基础(二十)用户创建、密码管理、用户锁定
  17. Python美股量化交易填坑记录——13c.Vegas隧道交易机器人(实盘记录)
  18. 【知识图谱】实践篇——基于知识图谱的《红楼梦》人物关系可视化及问答系统实践:part7项目优化与打包
  19. M1 Mac 上安装 python mysqlclient
  20. java 客户端打印_java如何获取客户端打印机 求教

热门文章

  1. 《计算机科学概论》—第1章1.3节计算工具与计算学科
  2. 总结2---万用表测量方波和正弦波的电压
  3. 2729: [HNOI2012]排队
  4. DataGrid小扩展
  5. vue2.0中的watch和计算属性computed
  6. Redis 存储SQL表格 方法
  7. 系统分区 ,硬盘格式化,
  8. windows bat 设置代理上网脚本bat
  9. 【BZOJ 1095】 [ZJOI2007]Hide 捉迷藏 括号序列
  10. zabbix-server无法启动