显示来自 RSS 提要的图像

Display Image from RSS Feed

我正在使用 rss-parser 解析 RSS 提要,在列表中显示结果。

数据添加到状态如下:

async getJobsData() {
    let feed = await parser.parseURL(
      "https://weworkremotely.com/categories/remote-design-jobs.rss"
    );

    this.setState({ data: feed.items });
  }

文本字段很简单,因为它们以 <pubDate>Mon, 20 May 2019 10:36:42 +0000</pubDate> 的形式出现,并使用 <span key={index}>{data.pubDate}</span> 添加到各自的列表项中。

虽然图片的响应格式不同。它作为第一项插入到通用 content 响应中。

title: [...]
pubDate: [...]
content: "<img src="https://we-work-remotely.imgix.net/logos/0015/7503/logo.gif?ixlib=rails-2.1.3&w=50&h=50&dpr=2&fit=fill&auto=compress" alt="Logo.gif?ixlib=rails 2.1" />

如何从该字段中仅提取 URL (https://we-work-remotely.imgix.net/logos/0015/7503/logo.gif?)?

您可以使用 HTML 解析器,例如https://www.npmjs.com/package/fast-html-parser 并获取 src 属性。

您可以使用 DOMParser 将文本表示解析为 DOM。

下面的代码片段将打印 img.src

const imgText = `<img src="https://we-work-remotely.imgix.net/logos/0015/7503/logo.gif?ixlib=rails-2.1.3&w=50&h=50&dpr=2&fit=fill&auto=compress" alt="Logo.gif?ixlib=rails 2.1" />`
const doc = new DOMParser().parseFromString(imgText, 'text/html')

console.log(doc.body.firstElementChild.src)