Home > Blockchain >  Nuxt filter Iframe src from YouTube embed code
Nuxt filter Iframe src from YouTube embed code

Time:11-25

I'm have a YouTube iframe video code which I'm getting from an API I get this:

 "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
                }
            ]

I want to only get in the response:

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

I'm using Axios to get the API and Nuxt after i wish to use the "src" in one video player like :

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

But I don't know how to filter only the "src" of the Iframe in Description from the API response.

CodePudding user response:

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
}

This will return only the url https://www.youtube.com/embed/4FZKdEZ4T5E

For your use case:


<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>
  • Related