一、split拆分法
//方法
GetUrlParam (paraName) {
var url = window.location.toString();
var arrObj = url.split("?");
if (arrObj.length > 1) {
var arrPara = arrObj[1].split("&");
var arr;
for (var i = 0; i < arrPara.length; i++) {
arr = arrPara[i].split("=");
if (arr != null && arr[0] == paraName) {
return arr[1];
}
}
return "";
} else {
return "";
}
}
// 用法:获取url拼接的参数 name
例:'https://www.baidu.com/#/Supply?item=6&name=张三&phone=18814789632'
let name = this.GetUrlParam("name")
//打印结果
console.log(name) //张三
二、正则表达式获取url地址
//方法
getQueryString(name) {
var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i');
var r = window.location.search.substr(1).match(reg);
if (r != null) {
return unescape(r[2]);
}
return null;
}
//用法:获取url拼接的参数 name
例:https://www.baidu.com?item=6&name=张三&phone=18814789632
let name = this.getQueryString('name') //引号里是需要获取的参数名
//打印结果
console.log(name) //张三
三、正则(推荐使用)
//方法
GetQueryString(name) {
var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
var r = window.location.search.substr(1).match(reg); //获取url中"?"符后的字符串并正则匹配
var context = "";
if (r != null)
context = decodeURIComponent(r[2]);
reg = null;
r = null;
return context == null || context == "" || context == "undefined" ? "" : context;
}
//用法:获取url拼接的参数 code
例:http://localhost:8081/?code=1111#/appeal
let code = this.GetQueryString('code') //引号为需要获取的参数名
//打印结果
console.log(code) //1111
最近又发现一个获取url上参数的方法
const sessionIdFunc=(key)=>{
const urlSessionId = new URLSearchParams(window.location.hash.slice(window.location.hash.indexOf('?')));
const paramSessionId= urlSessionId.get(key);
return paramSessionId
}
//使用
例:'https://www.baidu.com/#/Supply?item=6&name=张三&phone=18814789632'
let name= sessionIdFunc('name')