首页 > 解决方案 > 如何使用正则表达式解析 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 响应,而不是正则表达式数据。任何帮助是极大的赞赏。

标签: javascriptjqueryregexajax

解决方案


如果您的响应是一个字符串,那么您可以像这样使用string.match()

$.ajax(settings).done(function (response) {
  console.log(response.match(/(?=\[\{).*(\}\])/));
});

推荐阅读