站長博客:https://www.pipipi.net/web
URLSearchParams
瀏覽器兼容性能夠參考MDN(https://developer.mozilla.org...) 使用方法以下:api
var paramsString = "q=URLUtils.searchParams&topic=api"; var searchParams = new URLSearchParams(paramsString); //Iterate the search parameters. for (let p of searchParams) { console.log(p); } searchParams.has("topic") === true; // true searchParams.get("topic") === "api"; // true searchParams.getAll("topic"); // ["api"] searchParams.get("foo") === null; // true searchParams.append("topic", "webdev"); searchParams.toString(); // "q=URLUtils.searchParams&topic=api&topic=webdev" searchParams.set("topic", "More webdev"); searchParams.toString(); // "q=URLUtils.searchParams&topic=More+webdev" searchParams.delete("topic"); searchParams.toString(); // "q=URLUtils.searchParams"
JavaScript原生實現瀏覽器
function getParameterByName(name, url) { if (!url) url = window.location.href; name = name.replace(/[\[\]]/g, '\\$&'); var regex = new RegExp('[?&]' + name + '(=([^&#]*)|&|#|$)'), results = regex.exec(url); if (!results) return null; if (!results[2]) return ''; return decodeURIComponent(results[2].replace(/\+/g, ' ')); } //使用方法 //若是查詢參數爲?foo=chuangke&bar=&baz var foo = getParameterByName('foo'); // "chuangke" var bar = getParameterByName('bar'); // "" (present with empty value) var baz = getParameterByName('baz'); // "" (present with no value) var qux = getParameterByName('qux'); // null