欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

javascript获取地址栏参数/值

程序员文章站 2024-02-18 08:35:29
...
//URL: http://www.example.com/?var1=val1&var2=val2=val3&test=3&test=43&aaa=#2

//window.location.search will return "?var1=val1&var2=val2=val3&test=3&test=43&aaa="
//use the location.search, because # could be remove.

//refer:
//https://gist.github.com/alkos333/1771618
//http://papermashup.com/read-url-get-variables-withjavascript/
//http://jquery-howto.blogspot.com/2009/09/get-url-parameters-values-with-jquery.html

//1.
//getUrlVars() will return {var1: "val1", var2: "val2=val3", test: "43", aaa: ""}
function getUrlVars() {
  var vars = {};
  var parts = window.location.search.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(match, key ,value) {
    vars[key] = value;
  });
  return vars;
}
//2.
//getUrlVars() will return array ["var1", "var2", "test", "test", "aaa"]
//getUrlvars('var2') will return "val2=val3"
function getUrlVars(key) {
  var vars = [];
  var parts = window.location.search.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(match, key, value) {
    vars.push(key);
    vars[key] = value;
  });
  if (key) {
    return vars[key];
  }
  return vars;
}