Microsoft doesn’t make it easy to embed Youtube videos in your SharePoint website. Well thanks to http://forum.jquery.com/topic/change-youtube-and-yahoo-video-links-to-embedded-players there is an easy way to do it using jQuery. I know you’re shocked that I’m using jQuery.

I’ve slightly modified his script as it was wiping out everything on the screen as he had the $(this).replaceWith(mystring) outside of the if videoUrl !== null statement. I also updated it to work with SharePoint. If you paste a link address into a content editor it will automatically convert it into a link. So I have it looking for the a of the link and replace the whole link with the embed code. Oh you’re going to want this code to run in the very last “$(document).ready(function()” you can possibly spare. I have mine placed at the bottom of the master page.

Users need only to paste the youtube url “http://www.youtube.com/watch?v=” and save the page. That’s it! No special code, crazy web parts, importing text files with the html or other nonsense.

EDIT 4/26/2012: I’ve changed the code to use the new iframe embed rather then the old embed code. It’s cleaner and allows youtube to decided whether it renders flash or HTML 5 video.

//This check and function will replace all <a's> that have a "http://www.youtube.com/watch?v=" with an embed video player.
$("a").each(function() {
// get paragraph text
var mystring = $(this).text(); 
// regular expression for a youtube video
var expression = /http:\/\/(\w{0,3}\.)?youtube\.\w{2,3}\/watch\?v=[\w-]{11}/gi; 
// get an array of matched video urls
var videoUrl = mystring.match(expression);
   if (videoUrl !== null) {
   // for each video url change it to embedded
      for(count = 0; count < videoUrl.length; count++) {
	// replace url with embedded video
	mystring = mystring.replace(videoUrl[count], embedVideo(videoUrl[count]));      
      };
   //Only replace the <a's> that match the string.
   $(this).replaceWith(mystring);
   };
});
   
//This function will replace all a that has a http://www.youtube.com/watch?v= with an embed video player.
function embedVideo(content) {
      var youtubeUrl = content;
      var youtubeId = youtubeUrl.match(/=[\w-]{11}/);
      var strId = youtubeId[0].replace(/=/,'');
      var result = '<iframe width="400" height="248" src="http://www.youtube.com/embed/' + strId + '?rel=0" frameborder="0" allowfullscreen></iframe>';
      return result;
}

About these ads