Directly upload the code
//url 解析
const urlAnalysis = (url) => {
//通过?分割
const index = url.split("?");
//地址
const address = index[0];
//参数
const parameter = index[1];
//继续进行分割
const parameterArr = parameter.split("&");
//储存的数组
const resultArr = [];
parameterArr.forEach((item, index) => {
let r = item.split("=");
let obj = {
key: r[0],
value: r[1],
};
resultArr.push(obj);
});
let urlanalysisResults = {
url: address,
data: resultArr,
};
return urlanalysisResults;
};
It’s already packaged, just use it directly
analyze
It's actually a very simple operation
For example, if I define a value called url , it is
const url = "https://www.baidu.com?id=100&name=test"
So can I pass url.split("?") ? Make a split and it becomes two parts
const index = url.split("?")
[" https://www.baidu.com "," id=100&name=test "] He will return you this array
Then the first step is completed, we can directly get the string at subscript 1 of the array and perform an operation,
Perform another split on " id=100&name=test ". In this case, the splicing symbol is &.
const parameter = index[1].url.split("&");
So you can get the two arrays [" id=100 ", " name=test "], and then in the same way, split each item in the array, and set up a resultArr array to store it.
let resultArr = []
parameter.forEach((item, index) => {
let r = item.split("=");
let obj = {
key: r[0],
value: r[1],
};
resultArr.push(obj);
});
Then it's done. The structure in resultArr is the structure you want.
{
id:100,
name:"Test"
}
The above code has been encapsulated and can be used directly.