如何从Javascript中的URL获取值? 结果结果

问题描述

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

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

2/rooms?id=1

我得到的结果是:

import java.util.Arrays;
public class MyClass {
    
    private static final int[][] IDS =
    {
        { 20835,21608 },{ 21608,21609 },{ 20832,21602 },{ 21602,21603 },{ 20833,21605 },{ 21605,21606 },{ 21625,21623 },{ 21623,21624 },{ 20842,21620 },{ 21620,21621 }
    };
    
    public static void main(String args[]) {
      System.out.println(GiveMeAName(20835 ));
    }
    
    public static int GiveMeAName(int searchValue) {
        return Arrays.stream(IDS).filter(e -> e[0] == searchValue).map(e -> e[1]).findFirst().get();
    }
}

我要为 hotelId 变量获得的结果为2,变量 id 的结果为1。 我需要获取hotelId && id的全部值。

解决方法

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

因此,这是您必须使用的:

?hotelId=2/rooms?id=1
  1. 问号(?)后面的子字符串
  2. 由正斜杠(/)分隔
  3. 现在每对都将s?i替换为I
    • 这只会将rooms?id=之类的内容转换为roomId
  4. 您可以选择将任何类似于数字的值解析为整数
  5. 现在通过调用Object.fromEntries
  6. 将成对列表转换为对象

演示

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"
  }
}

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...