要在 JavaScript 中获取 URL 地址栏的参数,可以使用 URLSearchParams
对象,这个对象提供了一种非常方便的方法来解析查询字符串。下面是一些示例代码,展示了如何使用 URLSearchParams
获取 URL 参数:
获取查询参数
- 基本用法:
- 处理 Hash 部分的参数:
如果参数包含在#
后面(即哈希部分),需要手动解析:
- 封装成函数:
为了便于在项目中重复使用,可以封装成一个函数:
总结
使用 URLSearchParams
对象,可以方便地解析查询字符串中的参数。对于哈希部分的参数,需要手动解析并与查询字符串的参数进行合并。上述代码提供了一个完整的示例,展示了如何获取 URL 中的参数,并处理哈希部分的参数。