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
参考文章:
https://blog.csdn.net/weixin_41791737/article/details/117661471 // 最简单的方法:JS去除url中某个参数--正则表达式
https://tool.oschina.net/uploads/apidocs/jquery/regexp.html // 正则表达式全集
标签:return,URL,html,正则表达式,实例,url,https,const From: https://www.cnblogs.com/xuqichun/p/17343547.html