方法一:使用正则表达式
function getUrlParam(name) { let params_str = location.search.substring(1); var reg = new RegExp(`(^|&)${name}=([^&]*)(&|$)`, "i"); var result = params_str.match(reg); if (result === null) { return null; } // 对编码过 URI 进行解码 return decodeURIComponent(result[2]); }
方式二:使用 URLSearchParams,IE浏览器不兼容
function getUrlParam(name) { let pram = new URLSearchParams(location.search); return pram.get(name); }
方式三:手动解析-字符串拆分
function getUrlParam(name) { let params_str = location.search.substring(1); let params_dic = {}; params_str.split("&").forEach((item) => { let paramItem_list = item.split("="); if (paramItem_list.length === 2) { params_dic[paramItem_list[0]] = paramItem_list[1]; } }); return decodeURIComponent(params_dic[name]); }