如何解决如何从Javascript中的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
- 问号(
?
)后面的子字符串 - 由正斜杠(
/
)分隔 - 现在每对都将
s?i
替换为I
。- 这只会将
rooms?id=
之类的内容转换为roomId
- 这只会将
- 您可以选择将任何类似于数字的值解析为整数
- 现在通过调用
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"
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。