首页 > 解决方案 > 如何从 Javascript 中的 URL 获取值?

问题描述

我有一个带有一些 GET 参数的 URL,如下所示:

https://khanhjs.web.app/js/rooms/edit_rooms.html?hotelId=2/rooms?id=1 我试过这个方法:

const UrlParam = new URLSearchParams(window.location.search);
hotelId = UrlParam.get('hotelId');

我得到的结果是:

2/rooms?id=1

我想为hotelId变量得到的结果是2,变量id是1。我需要得到hotelId && id 的整个值。

标签: javascripturlurl-parameters

解决方案


由于您的 url 不太符合search要传递给的标准值,因此请URLSearchParams避免使用它并将该部分解析search为字符串。

所以,这就是你必须使用的:

?hotelId=2/rooms?id=1
  1. 问号 ( ?)后的子字符串
  2. 用正斜杠 ( /)分割
  3. 现在对于每一对,将 替换s?iI
    • 这只是将任何东西转换rooms?id=roomId
  4. 您可以选择将任何类似数字的值解析为整数
  5. 现在通过调用将对列表转换为对象Object.fromEntries

演示

const url = 'https://khanhjs.web.app/js/rooms/edit_rooms.html?hotelId=2/rooms?id=1';

const extractParams = (...path) => {
  return Object.fromEntries(new URL(path).search
    .substring(1)
    .split('/')
    .map(pair =>
      (([key, value]) => [
        key.replace(/s\?i/, 'I'),
        (!isNaN(value) ? parseInt(value, 10) : value)
      ])
     (pair.split('='))));
  
  console.log(searchParams);
  
};

console.log(extractParams(url));
.as-console-wrapper { top: 0; max-height: 100% !important; }

结果

{
  "hotelId": 2,
  "roomId": 1
}

递归救援!

或者,如果 URL 表示嵌套结构,您可以尝试递归。

const url = 'https://khanhjs.web.app/js/rooms/edit_rooms.html?hotelId=2/rooms?id=1';

const extractParams = (...path) => parse(new URL(path).search, {});

const parse = (params, result) => {
  if (params == null) return result;
  const index = params.indexOf('/');
  let head, tail;
  if (index !== -1) {
    head = params.substring(0, index);
    tail = params.substring(index + 1);
  } else {
    head = params;
    tail = null;
  }
  const [ root, pair ] = head.split('?')
  const [ key, value ] = pair.split('=');
  if (root === '') {
    result = { ...result, [key]: value };
  } else {
    result[root] = { ...result[root], [key] : value };
  }
  return parse(tail, result);
};

console.log(extractParams(url));
.as-console-wrapper { top: 0; max-height: 100% !important; }

结果

{
  "hotelId": "2",
  "rooms": {
    "id": "1"
  }
}

推荐阅读