【问题标题】:How to get the value from URL in Javascript?如何从 Javascript 中的 URL 获取值?
【发布时间】:2021-01-22 18:16:38
【问题描述】:

我有一个带有一些 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 的全部值。

【问题讨论】:

标签: javascript url url-parameters


【解决方案1】:

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

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

?hotelId=2/rooms?id=1
  1. 问号后的子字符串 (?)
  2. 用正斜杠分割 (/)
  3. 现在对于每一对,将s?i 替换为I
    • 这只是将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"
  }
}

【讨论】:

    猜你喜欢
    • 2020-09-18
    • 2020-09-05
    • 2020-05-14
    • 2012-03-31
    • 2012-09-09
    • 1970-01-01
    相关资源
    最近更新 更多