JavaScript 如何获取包含当前URL参数的对象
本文的目的是获取一个包含当前URL参数的对象。
示例:
Input: www.geeksforgeeks.org/search?name=john&age=27
Output: {
name: "john",
age: 27
}
Input: geeksforgeeks.org
Output: {}
为了实现这个目标,我们按照以下步骤进行操作。
1. 创建一个空对象。
2. 使用String.match()方法提取由”?”和”&”分隔的所有查询参数。我们使用正则表达式/([^?=&]+)(=([^&]*))/g
来实现这一点。
3. String.match()方法返回一个包含所有查询的数组。
4. 使用for…each循环迭代该数组,并在每次迭代时使用String.split()方法将值按”=”符号分割。该方法返回一个包含2个字符串的数组,第一个字符串是”=”符号左侧的部分,第二个字符串是”=”符号右侧的部分。
5. 将第一个字符串作为键,将第二个字符串作为该键在新创建的对象中的值。
6. 最后,返回新创建的对象。
示例:
function getAllParams(url) {
// Create an empty object
let obj = {};
// Extract the query params
let paramsArray = url.match(/([^?=&]+)(=([^&]*))/g)
// Check if there is one or more params
if (paramsArray) {
// Iterate the params array
paramsArray.forEach((query) => {
// Split the array
let strings = query.split("=")
// Assign the values to the object
obj[strings[0]] = strings[1]
})
}
// Return the object
return obj;
}
console.log(getAllParams(
"www.geeksforgeeks.org/search?name=john&age=27"))
console.log(getAllParams("geeksforgeeks.org"))
输出:
{
age: "27",
name: "john"
}
{}