Last active
August 29, 2015 14:10
-
-
Save Rplus/dbf6819202d368369827 to your computer and use it in GitHub Desktop.
get parameter by name form url location.search
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /// 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'); |
Author
Author
MDN 的方法
function loadPageVar (sVar) {
return decodeURI(window.location.search.replace(new RegExp("^(?:.*[&\\?]" + encodeURI(sVar).replace(/[\.\+\*]/g, "\\$&") + "(?:\\=([^&]*))?)?.*$", "i"), "$1"));
}
alert(loadPageVar("name"));
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
visual RexExp:
http://www.regexper.com/#.%2B%3F%5B%3F%26%5Dprop%3D(%5B%5E%26%5D*)