来自 YouTube 嵌入代码的 Nuxt 过滤器 Iframe src

Nuxt filter Iframe src from YouTube embed code

我有一个 YouTube iframe 视频代码,我从 API 得到了这个:

 "images": [
                {
                    "title": "",
                    "description": "<iframe width=\"560\" height=\"315\" src=\"https://www.youtube.com/embed/4FZKdEZ4T5E\" frameborder=\"0\" allow=\"accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture\" allowfullscreen></iframe>",
                    "file_extension": "jpeg",
                    "position": 0,
                    "url": "https://bucket-prod-01.s3.eu-west-1.amazonaws.com/uploads/content/7c085e8169d7b4d6bd863947e....jpeg",
                    "type": 0,
                    "link": "",
                    "id": 4760
                }
            ]

我只想在响应中得到:

src=\"https://www.youtube.com/embed/4FZKdEZ4T5E\"

我正在使用 Axios 来获取 API 和 Nuxt,因为我希望在一个视频播放器中使用“src”,例如:

<video-embed src="https://www.youtube.com/watch?v=s4ObxcdXoFE"></video-embed>

但我不知道如何从 API 响应中仅过滤说明中 Iframe 的“src”。

function getFirstUrlFromText(text) {
  // Find urls from text 
  // Will return this in your case: ['https://www.youtube.com/embed/4FZKdEZ4T5E"']
  const results = text.match(/(https?:\/\/[^\s]+)/g)

  let foundUrl = null

  // If found any url in text
  if (results) {
    // Remove " from all urls and get the first url
    foundUrl = results.map(el => el.replace('"', ''))[0]
  }

  return foundUrl
}

这将 return 只有 url https://www.youtube.com/embed/4FZKdEZ4T5E

对于您的用例:


<template>
  <div>
    <video-embed v-if="embedVideoUrl" :src="embedVideoUrl"></video-embed>
  </div>
</template>

<script>
export default {
  data() {
    return {
      embedVideoUrl: ''
    }
  },
  methods: {
    getVideo() {
      function getFirstUrlFromText(text) {
        // Find urls from text
        // Will return this in your case: ['https://www.youtube.com/embed/4FZKdEZ4T5E"']
        const results = text.match(/(https?:\/\/[^\s]+)/g)

        let foundUrl = null

        // If found any url in text
        if (results) {
          // Remove " from all urls and get the first url
          foundUrl = results.map(el => el.replace('"', ''))[0]
        }

        return foundUrl
      }

      try {
        const apiResponse = await $axios.$get('...')

        const firstResult = apiResponse.images[0]

        const embedVideoUrl = getFirstUrlFromText(firstResult.description)

        if (embedVideoUrl) {
          this.embedVideoUrl = embedVideoUrl
        }
      } catch (e) {
        // Handle error
        console.error(e)
      }
    }
  }
}
</script>