获取url中的参数方法,避免#的干扰,删除url指定参数(vue hash模式 有#删除指定参数问题)
function urlParse() {let url = window.location.search;let obj = {};let reg = /[?&][^?&]+=[^?&]+/g; // 正在表达式let arr = url.match(reg);// 得到数组:['?id=12345', '&a=b']if (...
·
function urlParse() {
let url = window.location.search;
let obj = {};
let reg = /[?&][^?&]+=[^?&]+/g; // 正在表达式
let arr = url.match(reg);
// 得到数组:['?id=12345', '&a=b']
if (arr) {
arr.forEach(item => {
let tempArr = item.substring(1).split('=');
let key = decodeURIComponent(tempArr[0]);
let val = decodeURIComponent(tempArr[1]);
obj[key] = val;
});
}
return obj;
}
// 使用正则表达式来匹配全路径下的?后的参数,避免#的干扰
const getUrlValue = function (name) {
let href = location.href
return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(href) || ["", ""])[1].replace(/\+/g, '%20')) || null
}
getUrlValue('inApp')
const getUrlParses = function () {
var url = window.location.href
// 如果url中没有传参直接返回空
if (url.indexOf('?') === -1) {
return null
}
var querys = url.substring(url.indexOf('?') + 1).split('&')
var result = {}
for (var i = 0; i < querys.length; i++) {
var temp = querys[i].split('=')
if (temp.length < 2) {
result = null
} else {
result[temp[0]] = temp[1]
}
}
console.log("getUrlParses -> result", result)
return result
}
删除url指定参数
function deleteParams(name){
var loca = window.location;
var baseUrl = loca.origin + loca.pathname + "?";
var query = loca.search.substr(1);
if (query.indexOf(name)>-1) {
var obj = {}
var arr = query.split("&");
for (var i = 0; i < arr.length; i++) {
arr[i] = arr[i].split("=");
obj[arr[i][0]] = arr[i][1];
};
delete obj[name];
var url = baseUrl + JSON.stringify(obj).replace(/[\"\{\}]/g,"").replace(/\:/g,"=").replace(/\,/g,"&");
return url
};
}
删除url指定参数(vue hash模式 有#删除指定参数问题)
function deleteParams(name) {
var loca = window.location;
var baseUrl = loca.origin + loca.pathname + loca.hash.substring(0, loca.hash.indexOf('?') + 1);
var query = loca.hash.substring(loca.hash.indexOf('?') + 1);
if (query.indexOf(name) > -1) {
var obj = {}
var arr = query.split("&");
for (var i = 0; i < arr.length; i++) {
arr[i] = arr[i].split("=");
obj[arr[i][0]] = arr[i][1];
};
delete obj[name];
var url = baseUrl + JSON.stringify(obj).replace(/[\"\{\}]/g, "").replace(/\:/g, "=").replace(/\,/g, "&");
return url
}
},
更多推荐
已为社区贡献13条内容
所有评论(0)