Skip to content

常用工具函数

获取 url 参数

特别注意url参数中携带了 '#' 符号,比如十六进制颜色值。

写法1

js
export function getUrlParams(url) {
  const params = {};

  // Match the part of the URL after the '?' or the hash
  const queryStringMatch = url.match(/[?&](.*)/);
  if (!queryStringMatch) return params;

  const queryString = queryStringMatch[1];

  // Split parameters by '&'
  const pairs = queryString.split("&");

  pairs.forEach((pair) => {
    const [key, value] = pair.split("=");

    // Decode key and value, preserving '#' in values like colors
    const decodedKey = decodeURIComponent(key);
    const decodedValue = decodeURIComponent(value || "").replace(/\+/g, " ");

    // Assign to params object
    params[decodedKey] = decodedValue;
  });

  return params;
}

// 示例
var url =
  "https://testm.fatiaoya.com/spaweb/vsdetail/badgedetail?badge_id=1188&uid=c7d994d5d0c93&bgColor=#ffffff&shareTitle=嘎嘎嘎~我又达成新成就了";
var params = extractUrlParams(url);
console.log(params);

// 输出示例
// {
//   badge_id: "1188",
//   uid: "c7d994d5d0c93",
//   bgColor: "#ffffff",
//   shareTitle: "嘎嘎嘎~我又达成新成就了"
// }

写法2

js
function getUrlParams(url) {
  const params = {};
  url.replace(/[?&]([^=&#]+)=([^&]*)/g, (_, key, value) => {
    params[decodeURIComponent(key)] = decodeURIComponent(value);
  });
  return params;
}
var url =
  "https://testm.fatiaoya.com/spaweb/vsdetail/#/badgedetail?badge_id=45&uid=7d994d5d0c93&bgColor=#ffffff&shareTitle=嘎嘎嘎~我又达成新成就了&t=123&name=okdd@@#";
console.log(getUrlParams(url));
// 输出示例
{
  badge_id: "45";
  bgColor: "#ffffff";
  name: "okdd@@#";
  shareTitle: "嘎嘎嘎~我又达成新成就了";
  t: "123";
  uid: "7d994d5d0c93";
}

Released under the MIT License.