写一个获取当前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=),则值将设置为空字符串。
  • 重复键: 如果一个键出现多次,则值将存储在一个数组中。

这个改进的版本更加健壮,可以处理各种边缘情况,并提供了一种更清晰的方式来访问查询参数。

posted @   王铁柱6  阅读(11)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
点击右上角即可分享
微信分享提示