Skip to content

Instantly share code, notes, and snippets.

@Rplus
Last active August 29, 2015 14:10
Show Gist options
  • Select an option

  • Save Rplus/dbf6819202d368369827 to your computer and use it in GitHub Desktop.

Select an option

Save Rplus/dbf6819202d368369827 to your computer and use it in GitHub Desktop.
get parameter by name form url location.search
/// via http://stackoverflow.com/a/5158301/3893926
/**
* get parameter by name form url location.search
* @param {string} name [description]
* @return {string | null} if name exist, return the para; or return null
*/
function getParameterByName(name) {
var match = RegExp('[?&]' + name + '=([^&]*)').exec(window.location.search);
return match && decodeURIComponent(match[1].replace(/\+/g, ' '));
}
// http://domain/?prodId=123&qwe=456
var prodId = getParameterByName('prodId');
@Rplus

Rplus commented Dec 8, 2014

Copy link
Copy Markdown
Author

@Rplus

Rplus commented Dec 10, 2014

Copy link
Copy Markdown
Author

MDN 的方法

function loadPageVar (sVar) {
  return decodeURI(window.location.search.replace(new RegExp("^(?:.*[&\\?]" + encodeURI(sVar).replace(/[\.\+\*]/g, "\\$&") + "(?:\\=([^&]*))?)?.*$", "i"), "$1"));
}

alert(loadPageVar("name"));

https://developer.mozilla.org/zh-CN/docs/Web/API/Window.location#.E4.BE.8B.E5.AD.90.236.EF.BC.9A.E8.8E.B7.E5.8F.96.E4.B8.80.E4.B8.AA.C2.A0window.location.search_.E9.94.AE.E5.80.BC.EF.BC.88key_value.EF.BC.89.EF.BC.9A

@Rplus

Rplus commented Dec 10, 2014

Copy link
Copy Markdown
Author

MDN 同場加映,
回傳整個 search query object,
可直接 object + key 查找

var oGetVars = new (function (sSearch) {
  if (sSearch.length > 1) {
    for (var aItKey, nKeyId = 0, aCouples = sSearch.substr(1).split("&"); nKeyId < aCouples.length; nKeyId++) {
      aItKey = aCouples[nKeyId].split("=");
      this[decodeURIComponent(aItKey[0])] = aItKey.length > 1 ? decodeURIComponent(aItKey[1]) : "";
    }
  }
})(window.location.search);

// alert(oGetVars.yourVar);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment