写一个获取当前url查询字符串中的参数的方法
function getQueryStringParams() {
const queryString = window.location.search;
const params = {};
if (queryString.length > 1) { // Check if query string exists (excluding "?")
const query = queryString.substring(1); // Remove the leading "?"
// Split the query string into key-value pairs
const pairs = query.split('&');
for (const pair of pairs) {
const [key, value] = pair.split('=');
// Decode URI components to handle special characters
const decodedKey = decodeURIComponent(key);
const decodedValue = decodeURIComponent(value || ''); // Handle cases where a key has no value
// Handle duplicate keys by storing values in an array
if (params.hasOwnProperty(decodedKey)) {
if (Array.isArray(params[decodedKey])) {
params[decodedKey].push(decodedValue);
} else {
params[decodedKey] = [params[decodedKey], decodedValue];
}
} else {
params[decodedKey] = decodedValue;
}
}
}
return params;
}
// Example usage:
const params = getQueryStringParams();
console.log(params);
// Accessing individual parameters:
if (params.hasOwnProperty('name')) {
console.log('Name:', params.name);
}
if (params.hasOwnProperty('age')) {
console.log('Age:', params.age);
}
//Example URL: http://example.com/?name=John%20Doe&age=30&city=New%20York&tags=a&tags=b&tags=c
//Output:
//{name: "John Doe", age: "30", city: "New York", tags: ["a", "b", "c"]}
这个函数getQueryStringParams()会返回一个包含所有查询参数的对象。它处理以下情况:
- 没有查询字符串: 如果URL中没有查询字符串,则返回一个空对象。
- URI编码: 使用
decodeURIComponent解码参数键和值,以便正确处理特殊字符和空格。 - 空值: 如果参数没有值(例如
?key=),则值将设置为空字符串。 - 重复键: 如果一个键出现多次,则值将存储在一个数组中。
这个改进的版本更加健壮,可以处理各种边缘情况,并提供了一种更清晰的方式来访问查询参数。
浙公网安备 33010602011771号