对于完整的url(包含http协议头)可使用:

  1. const getUrlParams = (url) => {
  2. const u = new URL(url);
  3. const s = new URLSearchParams(u.search);
  4. const obj = {};
  5. s.forEach((v, k) => (obj[k] = v));
  6. return obj;
  7. };

对于任意字符串可使用:

  1. const getUrlParams = (url) => {
  2. const arrSearch = url.split('?').pop().split('#').shift().split('&');
  3. let obj = {};
  4. console.log(arrSearch);
  5. arrSearch.forEach((item) => {
  6. const [k, v] = item.split('=');
  7. obj[k] = v;
  8. return obj;
  9. });
  10. return obj;
  11. };

判断是否有参数

  1. export const hasParams = (url: string) => {
  2. const arrSearch = (
  3. url
  4. .split('?')
  5. ?.pop()
  6. ?.split('#')
  7. ?.shift()
  8. ?.split('&') ?? []
  9. ).filter(item => item.indexOf('=') > -1);
  10. return (arrSearch?.length ?? 0) > 0;
  11. };

获取当前地址栏参数

  1. export const getUrlParams = (variable: string) => {
  2. const query = window.location.search.substring(1);
  3. const vars = query.split("&");
  4. for (var i = 0; i < vars.length; i++) {
  5. var pair = vars[i].split("=");
  6. if (pair[0] == variable) { return pair[1]; }
  7. }
  8. return false;
  9. }