获取 URL中参数
以url为例子,以下是几种常见的 JavaScript 获取 URL中参数name
的方式:
-
使用
URLSearchParams
对象:const urlParams = new URLSearchParams(window.location.search);
const name = urlParams.get('name');
console.log(name) -
使用正则表达式:
const url = window.location.href;
const regex = /[?&]name(=([^&#]*)|&|#|$)/;
const name = decodeURIComponent(url.match(regex)[2]);
console.log(name) -
使用
split()
方法:const url = window.location.href;
const params = url.split('?')[1].split('&');
let name;
for (let i = 0; i < params.length; i++) {
const param = params[i].split('=');
if (param[0] === 'name') {
name = decodeURIComponent(param[1]);
break;
}
}
console.log(name)