URL 正则表达式 实例

发布时间 2023-04-22 18:12:40作者: 转角遇到春

1. 获取URL指定参数

export function parseQueryString(name: string, url = location.search) {
  const reg = new RegExp(`(^|[?&])${name}=([^?&]*)(&|$)`, 'i');
  return decodeURIComponent(reg.exec(url)?.[2] || '');
}
const url = https://www.cnblogs.com/xuqichun/p/17343547.html?abc=1&id=8888888;
parseQueryString('id', url);

2. 对象拼接为URL参数格式

function urlParam(obj) {
  return Object.keys(obj).map((k) => {
    const value = obj[k];
    if (value === '') {
      return '';
    }
    return `${k}=${value}`;
  }).join('&');
}
urlParam({ a: 1, b: 2 });  //a=1&b=2

3. 删除URL中指定的参数

function deleteParam(name, url = location.search) {
   const reg = new RegExp(`([&]?${name}=[^&]*&?)`, 'g');
   return url.replace(reg, '')
}
const url = https://www.cnblogs.com/xuqichun/p/17343547.html?abc=1&id=8888888;
deleteParam('abc', url);

4. 获取路由名称( 问号前一个名称)

function getPageName(url = location.href) {
   const path = url?.match('[^/]+(?!.*/)');
   return path && path[0].split('?')[0];
}
const url = 'https://www.cnblogs.com/xuqichun/p/17343547.html?abc=1&id=8888888';
getPageName(url);  // 17343547.html