5

enter image description here

Trying to make something similar to facebook. I've created this javascript url pattern converter. Something like this could be triggered just as the user clicks on the submit button for a forum post - convert url's into embed html variants. Any ways to improve this?

http://jsfiddle.net/88Ms2/377/

var videoEmbed = {
    invoke: function(){

        $('body').html(function(i, html) {
            return videoEmbed.convertVideo(html);
        });

    },
    convertVideo: function(html){
        var pattern1 = /(?:http?s?:\/\/)?(?:www\.)?(?:vimeo\.com)\/?(.+)/g;
        var pattern2 = /(?:http?s?:\/\/)?(?:www\.)?(?:youtube\.com|youtu\.be)\/(?:watch\?v=)?(.+)/g;

        if(pattern1.test(html)){
            console.log("html", html);

           var replacement = '<iframe width="420" height="345" src="//player.vimeo.com/video/$1" frameborder="0" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe>';

           var html = html.replace(pattern1, replacement);
        }


        if(pattern2.test(html)){
              console.log("html", html);

           var replacement = '<iframe width="420" height="345" src="http://www.youtube.com/embed/$1" frameborder="0" allowfullscreen></iframe>';

            var html = html.replace(pattern2, replacement);
        } 


        return html;
    }
}






setTimeout(function(){
    videoEmbed.invoke();
},3000);
The Old County
  • 89
  • 13
  • 59
  • 129

3 Answers3

20

LATEST CODE ******** http://jsfiddle.net/88Ms2/378/

This mimics the facebook post feature - of turning a youtube, vimeo or image into a media based link. This will be useful in taking on

Interested in having the code enhanced.

var videoEmbed = {
    invoke: function(){

        $('body').html(function(i, html) {
            return videoEmbed.convertMedia(html);
        });

    },
    convertMedia: function(html){
        var pattern1 = /(?:http?s?:\/\/)?(?:www\.)?(?:vimeo\.com)\/?(.+)/g;
        var pattern2 = /(?:http?s?:\/\/)?(?:www\.)?(?:youtube\.com|youtu\.be)\/(?:watch\?v=)?(.+)/g;
        var pattern3 = /([-a-zA-Z0-9@:%_\+.~#?&//=]{2,256}\.[a-z]{2,4}\b(\/[-a-zA-Z0-9@:%_\+.~#?&//=]*)?(?:jpg|jpeg|gif|png))/gi;

        if(pattern1.test(html)){
           var replacement = '<iframe width="420" height="345" src="//player.vimeo.com/video/$1" frameborder="0" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe>';

           var html = html.replace(pattern1, replacement);
        }


        if(pattern2.test(html)){
              var replacement = '<iframe width="420" height="345" src="http://www.youtube.com/embed/$1" frameborder="0" allowfullscreen></iframe>';
              var html = html.replace(pattern2, replacement);
        } 


        if(pattern3.test(html)){
            var replacement = '<a href="$1" target="_blank"><img class="sml" src="$1" /></a><br />';
            var html = html.replace(pattern3, replacement);
        }          
        return html;
    }
}
The Old County
  • 89
  • 13
  • 59
  • 129
  • There is a problem with these regex if the value is already an embed url. For example: http://www.youtube.com/embed/GmdXJy_IdNw will be converted to http://www.youtube.com/embed/embed/GmdXJy_IdNw – Mr Zorn May 03 '16 at 16:47
  • @MrZorn to avoid this mistake use this regex: `/(?:http?s?:\/\/)?(?:www\.)?(?:youtube\.com|youtu\.be)\/(?:watch\?v=|embed\/)?(.+)/g` – coderocket Jun 03 '16 at 13:49
  • you saved me so much time ! Thanks ! but there's some redundant code, here it is corrected : `var pattern3 = /([-a-zA-Z0-9@:%_+.~#?&\/=]{2,256}\.[a-z]{2,4}\b(\/[-a-zA-Z0-9@:%_+.~#?&\/=]*)?(?:jpg|jpeg|gif|png))/gi;` – Sebastien H. Nov 24 '16 at 15:27
  • I made a gist that adds twitch, vocaroo, video URLs, and turns regular URLs into hyperlinks. I broke it into separate functions as well. https://gist.github.com/goosehub/0578867f7f5524d0b94ec13bbbf2cde2 – Goose Jan 04 '17 at 04:22
  • Thanks! I forked and fixed some regex issues, added support for youtube embed code and nocookie domain, restructured as a generic function and a generic convert table: http://jsfiddle.net/oriadam/v7b5edo8/ – oriadam Jan 30 '18 at 10:39
  • anyone can make regex for embed vimeo url of this "https://player.vimeo.com/video/520841497" – AbingPj Apr 08 '21 at 08:36
2

Here is a collection of functions that convert several types of media into embeds or other useful formats. Also handles input such as text link.com/file.jpg text. Credit to The Old County because this is built on top of his code.

function convert_youtube(input) {
  var pattern = /(?:http?s?:\/\/)?(?:www\.)?(?:youtube\.com|youtu\.be)\/(?:watch\?v=)?(\S+)/g;
  if (pattern.test(input)) {
    var replacement = '<iframe width="420" height="345" src="http://www.youtube.com/embed/$1" frameborder="0" allowfullscreen></iframe>';
    var input = input.replace(pattern, replacement);
    // For start time, turn get param & into ?
    var input = input.replace('&amp;t=', '?t=');
  }
  return input;
}

function convert_vimeo(input) {
  var pattern = /(?:http?s?:\/\/)?(?:www\.)?(?:vimeo\.com)\/?(\S+)/g;
  if (pattern.test(input)) {
   var replacement = '<iframe width="420" height="345" src="//player.vimeo.com/video/$1" frameborder="0" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe>';
   var input = input.replace(pattern, replacement);
  }
  return input;
}

function convert_twitch(input) {
  var pattern = /(?:http?s?:\/\/)?(?:www\.)?(?:twitch\.tv)\/?(\S+)/g;
  if (pattern.test(input)) {
   var replacement = '<iframe src="https://player.twitch.tv/?channel=$1&!autoplay" frameborder="0" allowfullscreen="true" scrolling="no" height="378" width="620"></iframe>';
   var input = input.replace(pattern, replacement);
  }
  return input;
}

function convert_vocaroo(input) {
  var pattern = /(?:http?s?:\/\/)?(?:www\.)?(?:vocaroo\.com\/i)\/?(\S+)/g;
  if (pattern.test(input)) {
   var replacement = '<object width="148" height="44"><param name="movie" value="http://vocaroo.com/player.swf?playMediaID=$1&autoplay=0"></param><param name="wmode" value="transparent"></param><embed src="http://vocaroo.com/player.swf?playMediaID=$1&autoplay=0" width="148" height="44" wmode="transparent" type="application/x-shockwave-flash"></embed></object>';
   var input = input.replace(pattern, replacement);
  }
  return input;
}

function convert_video_url(input) {
  var pattern = /([-a-zA-Z0-9@:%_\+.~#?&//=]{2,256}\.[a-z]{2,4}\b(\/[-a-zA-Z0-9@:%_\+.~#?&//=]*)?(?:webm|mp4|ogv))/gi;
  if (pattern.test(input)) {
    var replacement = '<video controls="" loop="" controls src="$1" style="max-width: 960px; max-height: 676px;"></video>';
    var input = input.replace(pattern, replacement);
  }
  return input;
}

function convert_image_url(input) {
  var pattern = /([-a-zA-Z0-9@:%_\+.~#?&//=]{2,256}\.[a-z]{2,4}\b(\/[-a-zA-Z0-9@:%_\+.~#?&//=]*)?(?:jpg|jpeg|gif|png))/gi;
  if (pattern.test(input)) {
    var replacement = '<a href="$1" target="_blank"><img class="sml" src="$1" /></a><br />';
    var input = input.replace(pattern, replacement);
  }
  return input;
}

// Run this function last
function convert_general_url(input) {
  // Ignore " to not conflict with other converts
  var pattern = /(?!.*")([-a-zA-Z0-9@:%_\+.~#?&//=;]{2,256}\.[a-z]{2,4}\b(\/[-a-zA-Z0-9@:%_\+.~#?&//=;]*))/gi;
  if (pattern.test(input)) {
    var replacement = '<a href="$1" target="_blank">$1</a>';
    var input = input.replace(pattern, replacement);
  }
  return input;
}
Goose
  • 4,764
  • 5
  • 45
  • 84
0

I share my answer here too. It is a bit different rom the others but may be useful in some contexts. Happy to get suggestions also on improvements.

Includes Youtube and Vimeo links, but not yet images

See also this Codepen here.

const convertLinks = ( input ) => {

  let text = input;
  const linksFound = text.match( /(?:www|https?)[^\s]+/g );
  const aLink = [];

  if ( linksFound != null ) {

    for ( let i=0; i<linksFound.length; i++ ) {
      let replace = linksFound[i];
      if ( !( linksFound[i].match( /(http(s?)):\/\// ) ) ) { replace = 'http://' + linksFound[i] }
      let linkText = replace.split( '/' )[2];
      if ( linkText.substring( 0, 3 ) == 'www' ) { linkText = linkText.replace( 'www.', '' ) }
      if ( linkText.match( /youtu/ ) ) {

        let youtubeID = replace.split( '/' ).slice(-1)[0];
        aLink.push( '<div class="video-wrapper"><iframe src="https://www.youtube.com/embed/' + youtubeID + '" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe></div>' )
      }
      else if ( linkText.match( /vimeo/ ) ) {
        let vimeoID = replace.split( '/' ).slice(-1)[0];
        aLink.push( '<div class="video-wrapper"><iframe src="https://player.vimeo.com/video/' + vimeoID + '" frameborder="0" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe></div>' )
      }
      else {
        aLink.push( '<a href="' + replace + '" target="_blank">' + linkText + '</a>' );
      }
      text = text.split( linksFound[i] ).map(item => { return aLink[i].includes('iframe') ? item.trim() : item } ).join( aLink[i] );
    }
    return text;

  }
  else {
    return input;
  }
}

this replaces long and clumsy links within plain texts to short clickable links within that text. (And also wraps videos in responsive iframes)

Example:

This clumsy link https://stackoverflow.com/questions/49634850/javascript-convert-plain-text-links-to-clickable-links/52544985#52544985 is very clumsy and this http://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split is not much better. This one www.apple.com is nice but www could be omitted

Becomes:

This clumsy link <a href="https://stackoverflow.com/questions/49634850/javascript-convert-plain-text-links-to-clickable-links/52544985#52544985" target="_blank">stackoverflow.com</a> is very clumsy and this <a href="http://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split" target="_blank">developer.mozilla.org</a> is not much better. This one <a href="http://www.apple.com" target="_blank">apple.com</a> is nice but www could be omitted

Is displayed as:

This clumsy link stackoverflow.com is very clumsy and this developer.mozilla.org is not much better. This one apple.com is nice but www can be removed

philipeachille
  • 185
  • 1
  • 6