当前位置:网站首页>获取地址url中的query参数指定参数方法
获取地址url中的query参数指定参数方法
2022-06-27 06:30:00 【搬砖的前端】
获取地址url中的query参数指定参数方法
方案一:(兼容性最好,但是有点长)
function getParam(name) {
//先获取#后面的参数
var getValue = function(name, str) {
//获取参数name的值
var reg = new RegExp("(^|!|&|\\?)" + name + "=([^&]*)(&|$)");
//再获取?后面的参数
var r = str.match(reg);
if (r != null) {
try {
return decodeURIComponent(r[2]);
} catch (e) {
console.log(e + "r[2]:" + r[2]);
return null;
}
}
return null;
};
var str = document.location.hash.substr(2);
var value = getValue(name, str);
if (value == null) {
str = document.location.search.substr(1);
value = getValue(name, str);
}
return value;
}
方案二:有兼容性(支持es6 的map就可以)
function getParams(key){
var ops = {
};
window.location.href.split('?')[1].split('&').map(i => ops[(i.split('=')[0])] = i.split('=')[1]);
return ops[key]
}
方案三:有兼容性(支持es6就可以)
- ts不可用,需要改下return那行
- ?. 表示为true就继续往后执行链式
function getParams(key){
var str = window.location.href.split('?')[1].split('&').filter(i => i.startsWith(key+'='));
return str?.[0]?.split('=')[1]
}
基本上主流浏览器都没问题,一般我用万能的第一种,但是有些长
边栏推荐
猜你喜欢

建模竞赛-光传送网建模与价值评估

JVM类加载机制

Centos7.9安装mysql 5.7,并设置开机启动

快速实现Thread Mesh组网详解

研究生数学建模竞赛-无人机在抢险救灾中的优化应用

Proxy reflect usage details

聊聊领域驱动设计

Assembly language - Wang Shuang Chapter 9 Principles of transfer instructions - Notes

从5秒优化到1秒,系统飞起来了...

C Primer Plus Chapter 11_ Strings and string functions_ Codes and exercises
随机推荐
Configuration of vscode korofileheader
JVM common instructions
Active learning
tracepoint
Spark sql 常用时间函数
LeetCode 0086. Separate linked list
multiprocessing.pool详解
427- binary tree (617. merge binary tree, 700. search in binary search tree, 98. verify binary search tree, 530. minimum absolute difference of binary search tree)
Dev++ 环境设置C语言关键字显示颜色
[QT dot] realize the watchdog function to detect whether the external program is running
JVM对象组成和存储
Assembly language - Wang Shuang Chapter 9 Principles of transfer instructions - Notes
Download CUDA and cudnn
Tidb database Quick Start Guide
2022 le fichier CISP - Pte (i) contient:
从5秒优化到1秒,系统飞起来了...
【LeetCode】Day90-二叉搜索树中第K小的元素
网关状态检测 echo request/reply
Visual Studio VS 快捷键使用大全
Redis 缓存穿透、缓存击穿、缓存雪崩