使用正则表达式筛选HTML响应内容
可以使用正则表达式来筛选responseText获取到的内容。例如,可以使用正则表达式匹配需要的内容,然后提取出来。具体的做法可以参考以下示例代码:
var xhr = new XMLHttpRequest();
xhr.open('GET', 'http://example.com/api');
xhr.onload = function() {
if (xhr.status === 200) {
var responseText = xhr.responseText;
// 使用正则表达式匹配需要的内容
var pattern = /<div class='content'>(.*)</div>/;
var match = pattern.exec(responseText);
if (match !== null) {
// 提取需要的内容
var content = match[1];
console.log(content);
} else {
console.log('匹配失败');
}
} else {
console.log('请求失败');
}
};
xhr.send();
在上面的示例代码中,我们使用正则表达式<div class='content'>(.*)</div>匹配<div class='content'>和</div>之间的内容,并使用exec()方法来提取需要的内容。如果匹配成功,就将提取出来的内容打印到控制台上。如果匹配失败,则打印出'匹配失败'。
原文地址: https://www.cveoy.top/t/topic/mOra 著作权归作者所有。请勿转载和采集!