- String.prototype.match() is used with the appropriate regular expression to get all key-value pairs
- Combine them into a single object using array.prototype.reduce ()
- Pass location.search as the argument to the current URL
const getURLParameters = (url) =>
(url.match(/([^?=&]+)(=([^&]*))/g) || []).reduce(
(a, v) => (
(a[v.slice(0, v.indexOf("="))] = v.slice(v.indexOf("=") + 1)), a
),
{}
);
getURLParameters("https://juejin.cn/"); // {}
getURLParameters("http://url.com/page?name=Tom&age=18"); // {name: "Tom", age: "18"}
Copy the code
= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =