86

I'm using this to convert YouTube URL to embed URL.

text(t).html().replace(/(?:http:\/\/)?(?:www\.)?(?:youtube\.com)\/(?:watch\?v=)?(.+)/g, '<iframe width="320" height="280" src="//www.youtube.com/embed/$1" frameborder="0" allowfullscreen></iframe>')

How can I make it ignore itself?

t = $('<div></div>').text(t).html().replace(/(?:http:\/\/)?(?:www\.)?(?:youtube\.com)\/(?:watch\?v=)?(.+)/g, '<iframe width="400" height="380" src="//www.youtube.com/embed/$1" frameborder="0" allowfullscreen></iframe>')

and an embedded link

<iframe width="560" height="315" src="//www.youtube.com/embed/1adfD9" frameborder="0" allowfullscreen></iframe>

Or, In other words, how can I make it work only on links like this and ignore everything else?

http://www.youtube.com/watch?v=1adfD9
www.youtube.com/watch?v=1adfD9
youtube.com/watch?v=1adfD9
1

11 Answers 11

175

I'd be inclined to simply grab the video ID per this question and use it to formulate your embed markup as you like.

http://jsfiddle.net/isherwood/cH6e8/

function getId(url) {
    const regExp = /^.*(youtu.be\/|v\/|u\/\w\/|embed\/|watch\?v=|&v=)([^#&?]*).*/;
    const match = url.match(regExp);

    return (match && match[2].length === 11)
      ? match[2]
      : null;
}
    
const videoId = getId('http://www.youtube.com/watch?v=zbYf5_S7oJo');
const iframeMarkup = '<iframe width="560" height="315" src="//www.youtube.com/embed/' 
    + videoId + '" frameborder="0" allowfullscreen></iframe>';

console.log('Video ID:', videoId)

Here's a more elaborate demo.

0
40

You can get the embed code by using the oembed API. There may be multiple variants of the YouTube URL and using regex may not be an optimal solution.

https://www.youtube.com/oembed?url=<URL>&format=<FORMAT>

example:

https://www.youtube.com/oembed?url=https://www.youtube.com/watch?v=gBrmnB5aOSI&format=json

The response you will get is this, from which you can use the HTML data for the iframe:

{
"type": "video",
"thumbnail_width": 480,
"provider_name": "YouTube",
"title": "Intro To Live Streaming on YouTube",
"thumbnail_height": 360,
"provider_url": "https://www.youtube.com/",
"version": "1.0",
"height": 270,
"author_name": "YouTube Creators",
"html": "<iframe width=\"480\" height=\"270\" src=\"https://www.youtube.com/embed/gBrmnB5aOSI?feature=oembed\" frameborder=\"0\" allow=\"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture\" allowfullscreen></iframe>",
"author_url": "https://www.youtube.com/user/creatoracademy",
"width": 480,
"thumbnail_url": "https://i.ytimg.com/vi/gBrmnB5aOSI/hqdefault.jpg"
}
0
11

I think the simplest solution is this:

ytUrl = "https://www.youtube.com/watch?v=DGIXT7ce3vQ"
// replace:
ytUrl.replace('/watch?v=', '/embed/')
7

I've been using this pair of functions to convert youtube links in a block of html from a wysiwyg editor into embedded iframes.

As with other solutions, this can still mangle some other html in the block.

  • works with multiple videos in one block of text
  • works with http or https links
  • works with both the direct url of the video youtube.com/watch?v=UxSOKvlAbwI and the share links youtu.be/UxSOKvlAbwI

code:

createYoutubeEmbed = (key) => {
  return '<iframe width="420" height="345" src="https://www.youtube.com/embed/' + key + '" frameborder="0" allowfullscreen></iframe><br/>';
};

transformYoutubeLinks = (text) => {
  if (!text) return text;
  const self = this;

  const linkreg = /(?:)<a([^>]+)>(.+?)<\/a>/g;
  const fullreg = /(https?:\/\/)?(www\.)?(youtube\.com\/watch\?v=|youtu\.be\/)([^& \n<]+)(?:[^ \n<]+)?/g;
  const regex = /(?:https?:\/\/)?(?:www\.)?(?:youtube\.com\/watch\?v=|youtu\.be\/)([^& \n<]+)(?:[^ \n<]+)?/g;

  let resultHtml = text;  

  // get all the matches for youtube links using the first regex
  const match = text.match(fullreg);
  if (match && match.length > 0) {
    // get all links and put in placeholders
    const matchlinks = text.match(linkreg);
    if (matchlinks && matchlinks.length > 0) {
      for (var i=0; i < matchlinks.length; i++) {
        resultHtml = resultHtml.replace(matchlinks[i], "#placeholder" + i + "#");
      }
    }

    // now go through the matches one by one
    for (var i=0; i < match.length; i++) {
      // get the key out of the match using the second regex
      let matchParts = match[i].split(regex);
      // replace the full match with the embedded youtube code
      resultHtml = resultHtml.replace(match[i], self.createYoutubeEmbed(matchParts[1]));
    }

    // ok now put our links back where the placeholders were.
    if (matchlinks && matchlinks.length > 0) {
      for (var i=0; i < matchlinks.length; i++) {
        resultHtml = resultHtml.replace("#placeholder" + i + "#", matchlinks[i]);
      }
    }
  }
  return resultHtml;
};

jsfiddle

4
  • i saw this was not working with specific time start in video (youtube.com/watch?v=B6ZQVXA0IRw&t=796s). Any help for this.
    – bring2dip
    Commented Dec 7, 2017 at 16:37
  • 1
    I’ll see if I can work that in. Turns out this snippet is mangling links out to YouTube videos that are meant to remain links (inside a fully formed a tag) so I need to fix that anyway. It’s on my todo list for today/tomorrow at least
    – phlare
    Commented Dec 7, 2017 at 16:41
  • 1
    It does create player from link that has the link as the hypertext <a href="youtu.be/fDVQPBvZOeo">https://youtu.be/fDVQPBvZOeo</…> if the link is like this <a href="youtu.be/fDVQPBvZOeo">video</a> it leave the link untouched, which is I guess the planing feature in both cases
    – 2046
    Commented Feb 10, 2018 at 15:50
  • its working good but only for ONE div=id, how to change it for classname? const htmlContent = document.getElementsByClassname(\'post\');//not working Commented Dec 22, 2022 at 4:24
7

Here is what I used to convert the YouTube URL to embed and make the video work.

<script>
    function myFunction() {
        var str = "https://www.youtube.com/watch?v=1adfD9";
        var res = str.split("=");
        var embeddedUrl = "https://www.youtube.com/embed/"+res[1];
        document.getElementById("demo").innerHTML = res;
    }
</script>

I hope this helps

3
2
function popYouTubeId(buttonid) {
    var youTubeUrl = $(buttonid).attr('data-url');
    var youTubeId;
    var regExp = /^.*(youtu.be\/|v\/|u\/\w\/|embed\/|watch\?v=|\&v=)([^#\&\?]*).*/;
    var match = youTubeUrl.match(regExp);
    if (match && match[2].length == 11) {
       youTubeId = match[2];
    } else {
        youTubeId = 'no video found';
   }
   $('#ytvideo').html('<div class="youtubepopup"><a class="closex">x</a><iframe width="560" height="315" src="//www.youtube.com/embed/' + youTubeId + '" frameborder="0" allowfullscreen></iframe></div>');
   $('a.closex').click( function(){
       $('.youtubepopup').remove();
   });
}

var buttonid;

$('.videobutton').click( function(){
    buttonid = '#'+$(this).attr('id');
    popYouTubeId(buttonid);
});

Some elaboration on isherwood's demo for your consideration. Simplifies, and packs more into the function for multiple use.

jsfiddle

1

This works fine for me on ReactJS

<iframe src={`https://www.youtube.com/embed/${url.split('='}[1]&autoplay=false`} controls allowfullscreen />
1

Who needs jQuery. Below is pure javascript code using URL() function to get v parameter from YouTube URL and insertAdjacentHTML() from replacing current <script> tag with <iframe>

<script>
const url = "https://www.youtube.com/watch?v=qRv7G7WpOoU";
const v = new URL(url).searchParams.get('v');

document.currentScript.insertAdjacentHTML(
  'beforebegin',
  `<h1>Video id=${v}</h1>` +
  `<iframe
      width="480" height="270"
      src="https://www.youtube.com/embed/${v}?feature=oembed"
      allowfullscreen></iframe>`
  );
</script>
0

Doesn't this way of getting the embedded id from desktop links seem easier to understand?

 const convertLinkToEmbedId = () => {
    const link = "https://www.youtube.com/watch?v=gBrmnB5aOSI&...";
    return link.substring(link.indexOf("=") + 1, link.indexOf("&"));
  };

You can then embed it this way:

 <iframe
      width='560'
      height='315'
      src={`https://www.youtube.com/embed/${convertLinkToEmbedId()}`}
      title='YouTube video player'
      frameborder='0'
      allow='accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture;fullscreen;'
    >
</iframe>

The problem is that this wouldn't work where there the id isn't between '=' and '&' :(

0

Created a Angular pipe for this case, which can simply be used wherever needed, it converts the link directly in the template.

HTML template:

<iframe
                width="560"
                height="315"
                [src]="PAST_YOUR_YTUBE_LINK_HERE | ytubePipe"
                title="YouTube video player"
                frameborder="0"
                allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share"
                allowfullscreen
              >
              </iframe>

Pipe ts file:

    import { Pipe, PipeTransform } from '@angular/core';
import { DomSanitizer, SafeResourceUrl } from '@angular/platform-browser';

@Pipe({
  name: 'ytubePipe',
  standalone: true,
})
export class YtubePipe implements PipeTransform {

  constructor(private sanitizer: DomSanitizer) {}

  createYoutubeEmbed(key: string): string {
    return `https://www.youtube.com/embed/${key}`;
  }

  transform(url: string): SafeResourceUrl {
    if (!url) {
      return '';
    }

    let videoId: string | null = null;
    const fullreg =
      /(https?:\/\/)?(www\.)?(youtube\.com\/watch\?v=|youtu\.be\/)([^& \n<]+)(?:[^ \n<]+)?/g;
    const match = fullreg.exec(url);
    if (match && match.length > 4) {
      videoId = match[4];
    }

    if (videoId) {
      const safeUrl = this.createYoutubeEmbed(videoId);
      return this.sanitizer.bypassSecurityTrustResourceUrl(safeUrl);
      // return safeUrl;
    }

    return this.sanitizer.bypassSecurityTrustResourceUrl(url);
    // return url;
  }
}
-2
 @if (path.Contains('&'))
                            path = path.Split('&')[0];

                <iframe width="690" height="400" src="@Model.YourModelNameHERE.Replace("watch?v=","embed/")" frameborder="0" allowfullscreen></iframe>

C# Razor pages solution!

Not the answer you're looking for? Browse other questions tagged or ask your own question.