javascript - 如何使用正则表达式解析 Ajax/Jquery 响应数据?
问题描述
如果我在标题中使用了不正确的术语,我深表歉意。我不知道该怎么说。
我正在使用 Ajax 进行 GET 调用,它以 html/txt/json 等形式的数据进行响应,所有这些都在一个文件中。我试图只提取 [{ }] 之间的内容。
我已经成功地使用下面的正则表达式来实现这一点,使用https://regexr.com:
(?=\[\{).*(\}\])
在我的 GET 调用返回的此响应数据中:
Lots of random text, random html, etc.
[{There is text in here hello world}]
Lots of random text, random html, etc.
如您所见,此正则表达式将正确提取:
[{There is text in here hello world}]
这很好用!但是我似乎无法弄清楚在收到响应后如何自动解析数据。我目前正在尝试:
$.ajax(settings).done(function (response) {
console.log(response.replace(/(?=\[\{).*(\}\])/));
});
但这行不通。我完全错了吗?它只输出完整的 GET 响应,而不是正则表达式数据。任何帮助是极大的赞赏。
解决方案
如果您的响应是一个字符串,那么您可以像这样使用string.match():
$.ajax(settings).done(function (response) {
console.log(response.match(/(?=\[\{).*(\}\])/));
});
推荐阅读
- typescript - 带有泛型的 Typescript 重载函数,类似于 Promise.all
- r - 在圆形直方图中仅显示给定的角度范围
- python - 使用刷新令牌发出新的访问令牌后继续请求流程
- authentication - 寻找有关实现单次使用令牌以进行登录的反馈
- apache - 如何使用 ssl 在子域上设置 phpmyadmin
- android - 使用 minifyEnabled 膨胀类 mapbox MapView 时出错
- regex - 如何使用正则表达式创建固定数字组?
- azure-iot-hub - IoT 客户端如何向 IoT 中心报告更改的属性?
- python - 使用 ruamel.yaml.scalarstring.DoubleQuotedScalarString 时,如何防止新行 \ 字符输出到 YAML?
- sql-server - GROUP BY 和日期时间范围之间的聚合