JSFiddle - React, Tailwind, and code Playground

by isherwood

HTML

<div>Enter a YouTube URL:
    <input id="myUrl" type="text" value="http://www.youtube.com/watch?v=zbYf5_S7oJo" />
</div>
<div>
    <button id="myBtn">Go</button>
</div>
<div>YouTube ID: <span id="myId"></span>

</div>
<div>Embed code: <pre id="myCode"></pre></div>

<div>This is an answer to <a target="_blank" href="http://stackoverflow.com/questions/21607808/convert-a-youtube-video-url-to-embed-code/21607897#21607897">a question on Stack Overflow</a>.</div>

CSS

#myId {
    color: orange;
}
input {width: 300px;}

JavaScript

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

    if (match && match[2].length == 11) {
        return match[2];
    } else {
        return 'error';
    }
}

var myId;

$('#myBtn').click(function () {
    var myUrl = $('#myUrl').val();
    myId = getId(myUrl);
    
    $('#myId').html(myId);
    
    $('#myCode').html('<iframe width="560" height="315" src="//www.youtube.com/embed/' + myId + '" frameborder="0" allowfullscreen></iframe>');
});