Skip to content

Instantly share code, notes, and snippets.

@srestraj
Last active May 16, 2023 18:57
Show Gist options
  • Save srestraj/0e0e308ddcd1ae5f8835e07bd638374c to your computer and use it in GitHub Desktop.
Save srestraj/0e0e308ddcd1ae5f8835e07bd638374c to your computer and use it in GitHub Desktop.
Vue.js filter to extract YouTube, Vimeo or Dailymotion thumbnail using the video URL

Vue.js filter to extract thumbnail from a YouTube, Vimeo or Dailymotion video

Add the following code to your template videos.vue
<template>
  <div>
    <label for="videourl">
      Vimeo or YouTube URL
    </label>
    <br/>
    <input type="text" v-model="videoURL" placeholder="Enter URL" id="videourl">

    <div v-if="videoURL != ''">
      Extracted Thumbnail: <br/>
      <img :src="videoURL | extractThumbnail" />
    </div>
  </div>
</template>
<script>

export default {
  data() {
    return {
      videoURL: ""
    };
  },
  filters: {
    extractThumbnail: function (image) {
      if (!image) return "";
      // regex to check the URL
      const regex = /^(http(s)??\:\/\/)?(www\.)?((youtube\.com\/watch\?v=)|(youtu.be\/)|(vimeo\.com\/)|(youtube\.com\/shorts\/)|(dailymotion\.com\/))?/i;
      let vimeoURL = "vimeo.com";
      let dailymotionURL = "dailymotion.com";
      let path = "";

      if (image.includes(vimeoURL)) {
        path = "https://" + image.replace(regex, "vumbnail.com/");
        return path + ".jpg";
      } else if (image.includes(dailymotionURL)) {
        path = image.replace(regex, "https://www.dailymotion.com/thumbnail/");
        return path;
      } else {
        path = "https://" + image.replace(regex, "img.youtube.com/vi/");
        return path + "/hqdefault.jpg"; // for high quality videos, you can use maxresdefault.jpg
      }
    }
  }
}
</script>

Note: This is for Vue 2. For Vue 3, check this out

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment