5

I'm trying to take a textarea input that takes any YouTube URL as the input and embed the video much like Facebook does.

I have:

var text = $('#content').val().split(' ');
    for (i = 0; i < text.length; i++) {
        var test = text[i].indexOf('youtube.com/watch');
        var check = text[i].indexOf('[youtube=');

        if (test != -1 && check == -1) {
            var ytid = text[i].substring(text[i].lastIndexOf('=') + 1);
            text[i] = '[youtube=' + ytid + ']';
        }
    }
var boxval = text.join(' ').trim();

which takes any YouTube URL and makes it into a [youtube=videoid]. Problem then is that when a URL is submitted with a <br> or a \n at the end it adds the ] afterwards.

Anyone know of a better way?

Yi Jiang
  • 49,435
  • 16
  • 136
  • 136
Ryan
  • 51
  • 1
  • 2
  • your question is incomplete i think "then i use ....." – jimy Mar 25 '11 at 07:49
  • Your logic will not work for a URL such as `http://www.youtube.com/watch?v=gzDS-Kfd5XQ&feature=youtube_gdata_player`, although it is a legit YouTube video URL. – Salman A Mar 25 '11 at 09:22

4 Answers4

3

Regular expressions to the rescue:

var text = (
"http://www.youtube.com/watch?v=gzDS-Kfd5XQ\n" +
"http://www.youtube.com/watch?v=gzDS-Kfd5XQ&feature=youtube_gdata_player\n" +
"http://www.youtube.com/watch?feature=youtube_gdata_player&v=gzDS-Kfd5XQ\n" +
"http://www.youtube.com/watch?v=gzDS-Kfd5XQ http://www.youtube.com/watch?v=gzDS-Kfd5XQ"
).split(/\s+/);
for (var i = 0; i < text.length; i++) {
    var url = text[i];
    if (/^https?\:\/\/.+/i.test(url)) {
        var temp = /[\?\&]v=([^\?\&]+)/.exec(url);
        if (temp) {
            text[i] = '[youtube=' + temp[1] + ']';
        } else {
            text[i] = "URL found but does not contain video id";
        }
    } else {
        // other case left as an exercise
    }
}
alert(text.join('\n'));

Code borrowed from here.

Salman A
  • 262,204
  • 82
  • 430
  • 521
3

A similar question was recently asked (but that question wanted a PHP solution). Here is a JavaScript version of my solution to that question:

// Linkify youtube URLs which are not already links.
function linkifyYouTubeURLs(text) {
    /* Commented regex (in PHP syntax)
    $text = preg_replace('%
        # Match any youtube URL in the wild.
        (?:https?://)?   # Optional scheme. Either http or https
        (?:www\.)?       # Optional www subdomain
        (?:              # Group host alternatives
          youtu\.be/     # Either youtu.be,
        | youtube\.com   # or youtube.com
          (?:            # Group path alternatives
            /embed/      # Either /embed/
          | /v/          # or /v/
          | /watch\?v=   # or /watch\?v=
          )              # End path alternatives.
        )                # End host alternatives.
        ([\w\-]{10,12})  # $1: Allow 10-12 for 11 char youtube id.
        \b               # Anchor end to word boundary.
        [?=&\w]*         # Consume any URL (query) remainder.
        (?!              # But don\'t match URLs already linked.
          [\'"][^<>]*>   # Not inside a start tag,
        | </a>           # or <a> element text contents.
        )                # End negative lookahead assertion.
        %ix', 
        '<a href="http://www.youtube.com/watch?v=$1">YouTube link: $1</a>',
        $text);
    */
    // Here is the same regex in JavaScript literal regexp syntax:
    return text.replace(
        /(?:https?:\/\/)?(?:www\.)?(?:youtu\.be\/|youtube\.com(?:\/embed\/|\/v\/|\/watch\?v=))([\w\-]{10,12})\b[?=&\w]*(?!['"][^<>]*>|<\/a>)/ig,
        '<a href="http://www.youtube.com/watch?v=$1">YouTube link: $1</a>');
}

You can easily modify the replacement string to convert to a BBCode rather than HTML.

Community
  • 1
  • 1
ridgerunner
  • 33,777
  • 5
  • 57
  • 69
1

Use jQuery.trim to strip the whitespace off the ytid variable

ChrisR
  • 14,370
  • 16
  • 70
  • 107
0

Try using a querystring parsing helper method:

var boxval = getParameterByName("v", $('#content').val());

Helper method (borrowed from here):

function getParameterByName(name, url)
{
  name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
  var regexS = "[\\?&]" + name + "=([^&#]*)";
  var regex = new RegExp(regexS);
  var results = regex.exec(url);
  if(results == null)
    return "";
  else
    return decodeURIComponent(results[1].replace(/\+/g, " "));
}
Community
  • 1
  • 1
Chad Levy
  • 10,032
  • 7
  • 41
  • 69