javascript - 如何从javascript中的url中提取参数
问题描述
我有这个chrome.identity.getRedirectURL()
函数提供的 url
https://jjjnkdmnhdhmfjdlmbljoiclmbojbiec.chromiumapp.org/#access_token=BQDhJnhA4NV2V-2Cn5xYwQyPz4QI5EdY3cu5nNqfgvVt4p4K8fKYtmlfp8ZQYS65ww2rUAZQ7chyZnPDZLlKJEyCfZBRxtr6Q1FpRe9UuiTJ2hT9SMNb-icodIc-I9ADauULDf4JVqvVXoHz1hWvpDWnqln8Yus&token_type=Bearer&expires_in=3600
我需要获取access_token
参数值来存储令牌并稍后与 spotify api 一起使用。我可以在 javascript 中使用的最佳方法是什么?
解决方案
如果您有类似的网址https://some-url?access_token=1234
,可以使用URLSearchParams
.
// window location search returns '?access_token=1234' if the url is 'https://some-url?access_token=1234'
const params = new URLSearchParams(window.location.search);
const token = params.get('access_token');
更新正则表达式
const x = new RegExp(/(#access_token=).*?(&)+/);
const str = 'https://jjjnkdmnhdhmfjdlmbljoiclmbojbiec.chromiumapp.org/#access_token=BQDhJnhA4NV2V-2Cn5xYwQyPz4QI5EdY3cu5nNqfgvVt4p4K8fKYtmlfp8ZQYS65ww2rUAZQ7chyZnPDZLlKJEyCfZBRxtr6Q1FpRe9UuiTJ2hT9SMNb-icodIc-I9ADauULDf4JVqvVXoHz1hWvpDWnqln8Yus&token_type=Bearer&expires_in=3600';
// Use String.prototype.match and pass the Regex
const result = String(str).match(x);
console.log(result);
// returns
[
"#access_token=BQDhJnhA4NV2V-2Cn5xYwQyPz4QI5EdY3cu5…9SMNb-icodIc-I9ADauULDf4JVqvVXoHz1hWvpDWnqln8Yus&",
"#access_token=", "&",
index: 57,
input: "https://jjjnkdmnhdhmfjdlmbljoiclmbojbiec.chromiuma…1hWvpDWnqln8Yus&token_type=Bearer&expires_in=3600",
groups: undefined
]
// Access the matching substring if there is one using
result[0];
// "#access_token=BQDhJnhA4NV2V-2Cn5xYwQyPz4QI5EdY3cu5nNqfgvVt4p4K8fKYtmlfp8ZQYS65ww2rUAZQ7chyZnPDZLlKJEyCfZBRxtr6Q1FpRe9UuiTJ2hT9SMNb-icodIc-I9ADauULDf4JVqvVXoHz1hWvpDWnqln8Yus&"
请注意,此正则表达式包含开头和结尾#
。&
推荐阅读
- html - Angular ng serve 不在本地主机上托管站点
- javascript - 如何使python lambda返回逗号运算符最后一个
- javascript - 是否可以在 NodeJs 中要求子 sdk 库?
- php - 如何在句子前剪切内容?
- javascript - Reactjs 函数未正确返回多个值:TypeError: undefined is not iterable (cannot read property Symbol(Symbol.iterator))
- c# - 创建文件夹时路径中的非法字符
- android - C# Xamarin.Forms,创建一个后台服务来循环 HTTP 请求和推送通知
- oauth-2.0 - 与 Keycloak 身份验证插件集成时,无法从 rest 客户端调用 nuxeo rest api
- reactjs - 没有设置状态或异步,但仍然“无法在未安装的组件上执行状态更新”错误
- sqlite - Chrome 版本 75.0.3770.80(官方构建)(64 位) - 无法开始事务(3850 磁盘 I/O 错误)