当前位置:网站首页>Get the parameters in the URL and the interchange between parameters and objects
Get the parameters in the URL and the interchange between parameters and objects
2022-06-25 14:23:00 【jason_ renyu】
Now native h5 There are not many projects , however url There are not many operations such as parameter transfer , Here is for those in need , Offer a little help .
Don't talk much, just go to the code :
obtain URL And turn it into an object
/** * analysis url All parameter information in * @param url {String} Incoming address url, Default to the currently accessed page window.location.href * @returns {Object} return url Parameters Object Data objects , No parameter scope will be empty {} */
const getUrlParams = (url = window.location.href) => {
const searchIndex = url.lastIndexOf('?');
const search = url.substring(searchIndex + 1);
if (searchIndex < 0 || !search || (search && !/=/.test(url))) {
return {
errMsg: ' At present url The parameter is empty. ',
errHref: url
}
}
const result = search.split('&').map(s => {
if (/=/.test(s)) {
return s;
}
return s + '=';
});
const resultStr = result.join('&');
return JSON.parse(`{"${
decodeURIComponent(resultStr).replace(/"/g, '\\"').replace(/&/g, '","').replace(/=/g, '":"')}"}`);
}
Example
// Example
console.log(' Parameters in the current link :', parseQueryString());
If url No parameters , Will return to empty {}, If you don't use some js Code base or tool , To judge that the object is empty, a method is also given here , Hope to useful :
Determines if the object is null
/** * Judge whether the object is empty * @param {Object} obj The incoming object * @returns If the object is empty, return true, Is not empty is false */
const isEmptyObj = (obj) => {
if (!obj) {
return true;
}
const objKeys = Object.keys(obj);
if (objKeys.length > 0) {
return false;
}
return true;
}
Please watch carefully when using , Object is null and returns true, Don't be wrong
Object to URL Parameter splicing method of
/** * * @desc Object serialization * @param {Object} obj * @return {String} */
const stringfyQueryString = (obj) => {
if (!obj) return '';
let pairs = [];
for (let key in obj) {
let value = obj[key];
if (value instanceof Array) {
console.log(' The contents of the cycle ', value);
for (let i = 0; i < value.length; ++i) {
pairs.push(encodeURIComponent(key + '[' + i + ']') + '=' + encodeURIComponent(value[i]));
}
continue;
}
pairs.push(encodeURIComponent(key) + '=' + encodeURIComponent(obj[key]));
}
return pairs.join('&');
}
Example
// Example
const paramObj = {
name: 'zhangsan',
age: 12,
local: 'zhouer'
};
console.log(' Conversion completed ', stringfyQueryString(paramObj));
The above hope to help you
边栏推荐
- Deeply understand the mathematics behind deep neural networks (mysteries of neural networks Part I)
- The best screenshot tool in the world, color absorption tool snipaste
- Error1822 and error1824 are displayed in the database
- 国信证券股票账户开户安全吗?请问。
- 让PyTorch训练速度更快,你需要掌握这17种方法
- Deconstruction assignment of variables
- Kubernetes cluster construction of multiple ECS
- 第一次读 “Clean” 系列,并没有觉得这是一本多好的书
- 当了六年程序员第一次搞懂微服务架构的数据一致性,真不容易
- Kubernetes cluster construction of multiple ECS
猜你喜欢

一次性讲清楚 Handler 可能导致的内存泄漏和解决办法 | 开发者说·DTalk

shell 字符串变量

还没弄明白微服务数据架构事务管理+ACID+一致性+CAP+BASE理论吗,看完彻底解决疑惑

Les neuf caractéristiques de la parole et les neuf temps en anglais

Why should programmers be softer?

What if the CPU temperature of Dell computer is too high

使用调试工具调试博图TCP连接所遇到的问题

Experts' suggestions | 8 measures to accelerate your innovative career planning and growth

第一次读 “Clean” 系列,并没有觉得这是一本多好的书

Dialogue: recommended system quick start route and summary of knowledge points
随机推荐
Where can the brightness of win7 display screen be adjusted
Deconstruction assignment of variables
"Mobile cloud Cup" computing power network application innovation competition is in hot registration!
解决报错:Creating window glfw ERROR: GLEW initalization error: Missing GL version
分享自己平時使用的socket多客戶端通信的代碼技術點和軟件使用
K-line diagram 24 classic diagrams (shadow)
Mise en place d'un Cluster kubernets avec plusieurs serveurs Cloud
Les neuf caractéristiques de la parole et les neuf temps en anglais
JVM 用工具分析OOM经典案例
Windows下MySQL的安装和删除
Installation and removal of MySQL under Windows
算力&NFT交易平台F3.xyz旗下独家权益NFT项目Hash Eagle将盛大发行
Sigmoid function sigmoid derivation
Summary of common functions in Oracle Database
多臺雲服務器的 Kubernetes 集群搭建
Untiy force refresh UI
Experts' suggestions | 8 measures to accelerate your innovative career planning and growth
国信证券股票开户是安全的吗?
Deploy eve-ng with KVM virtualization
打新债是不是不安全