当前位置: 首页> 教育> 培训 > 网址制作公司_房产发布平台有哪些_五年级上册优化设计答案_网络推广公司有哪些

网址制作公司_房产发布平台有哪些_五年级上册优化设计答案_网络推广公司有哪些

时间:2025/7/27 14:15:32来源:https://blog.csdn.net/wangshifan116/article/details/144943057 浏览次数:0次
网址制作公司_房产发布平台有哪些_五年级上册优化设计答案_网络推广公司有哪些

方法1:现代浏览器都支持 URL 和 URLSearchParams 对象,可以很方便地从URL中提取参数

// 假设当前URL为 "https://example.com/?name=John&age=30"
const url = new URL(window.location.href); // 或者你可以直接传入一个URL字符串
const name = url.searchParams.get('name'); // "John"
const age = url.searchParams.get('age'); // "30"console.log(name, age);

方法2:使用正则表达式

可以使用正则表达式匹配URL参数,这种方法相对较低效且较复杂,但也可以做到。

function getQueryParam(name) {const regex = new RegExp('[?&]' + name + '=([^&#]*)', 'i');const results = regex.exec(window.location.href);return results ? decodeURIComponent(results[1]) : null;
}// 假设当前URL为 "https://example.com/?name=John&age=30"
const name = getQueryParam('name'); // "John"
const age = getQueryParam('age'); // "30"console.log(name, age);

方法3:使用 split 和 reduce

可以通过 split 方法手动拆分查询参数,并用 reduce 将其转化为对象。

function getQueryParams() {return window.location.search.substring(1) // 去掉 ?.split('&') // 按 & 拆分.reduce((params, param) => {const [key, value] = param.split('=');params[decodeURIComponent(key)] = decodeURIComponent(value || '');return params;}, {});
}// 假设当前URL为 "https://example.com/?name=John&age=30"
const params = getQueryParams();
const name = params['name']; // "John"
const age = params['age']; // "30"console.log(name, age);

方法4:使用 location.search 和自定义函数

在 location.search 上构建自己的解析函数,此方法比较简单。

function getQueryParameter(name) {const params = new URLSearchParams(location.search);return params.get(name);
}// 假设当前URL为 "https://example.com/?name=John&age=30"
const name = getQueryParameter('name'); // "John"
const age = getQueryParameter('age'); // "30"console.log(name, age);

关键字:网址制作公司_房产发布平台有哪些_五年级上册优化设计答案_网络推广公司有哪些

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

责任编辑: