javascript - 如何从 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 的整个值。
解决方案
由于您的 url 不太符合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"
}
}
推荐阅读
- spring-boot - Eureka 服务器状态 URL 显示未识别的主机名
- react-typescript - 使用 reactjs 实时更新 scchart 数据
- android - 在当前主题中找不到“@attr/shapeAppearanceSmallComponent”
- javascript - Web 推送响应未从节点服务器返回有效负载正文
- python - 使用 textwrap 函数时打印文字空行
- identityserver4 - Blazor WASM - 身份角色声明
- git - Git 命令获取存储库的提交计数
- matlab - MATLAB:在我的 ODE 系统中使用符号数组时出错
- ratchet - 如何在 cloudways 服务器中启动 Ratchet websocket 以启动聊天应用程序
- javascript - 将元素放在其他元素之上(创建叠加层)