JS提取url中的参数值

代码先行

var urlParams;
(window.onpopstate = function () {
    var match;
    var pl = /\+/g; // Regex for replacing addition symbol with a space
    var search = /([^&=]+)=?([^&]*)/g;
    var decode = function (s) {
        return decodeURIComponent(s.replace(pl, " "));
    }
    var query = window.location.search.substring(1);
    urlParams = {};
    while (match = search.exec(query))
        urlParams[decode(match[1])] = decode(match[2]);
})();

如果你不需要使用IE,可以更简单:[兼容性参考]

var urlParams = new URLSearchParams(window.location.search);
var myParam = urlParams.get('myParam');
You Might Also Like
发表评论