Here's one way of doing it:
function linkYT(el) {
if (!el) {
return false;
}
else {
var children = el.childNodes,
text = [];
for (var i=0, len=children.length; i<len; i++){
var cur = children[i],
nType = cur.nodeType,
content = cur.nodeValue,
url = 'http://www.youtube.com/embed/';
if (nType == 3 && content.indexOf('youtube.com') > -1) {
var embed = content.trim().match(/v=(\w+)/)[1],
iframe = document.createElement('iframe');
iframe.src = url + embed;
el.insertBefore(iframe, cur.nextSibling);
cur.parentNode.removeChild(cur);
}
}
}
}
var el = document.getElementById('content');
linkYT(el);
JS Fiddle demo.
Please be aware there is no sanity-checking at all, and this approach requires that the video's identifier is prefaced with v= and terminated with a non-alphanumeric character.
I've tested and verified only in Opera 12, and Chromium 19.
To account for one other form of YouTube URL format:
function createIframe(embed, parent, after, url){
if (!embed || !parent || !after) {
return false;
}
else {
url = url ? url : 'http://www.youtube.com/embed/';
var iframe = document.createElement('iframe');
iframe.src = url + embed;
parent.insertBefore(iframe, after.nextSibling);
parent.removeChild(after);
}
}
function linkYT(el) {
if (!el) {
return false;
}
else {
var children = el.childNodes,
text = [];
for (var i=0, len=children.length; i<len; i++){
var cur = children[i],
nType = cur.nodeType,
content = cur.nodeValue,
url = 'http://www.youtube.com/embed/';
if (nType == 3) {
if (content.indexOf('youtube.com') > -1) {
var embed = content.trim().match(/v=(\w+)/)[1];
createIframe(embed, el, cur);
}
else if (content.indexOf('youtu.be') > -1) {
var embed = content.trim().match(/be\/(\w+)/)[1];
createIframe(embed, el, cur);
}
}
}
}
}
var el = document.getElementById('content');
linkYT(el);
JS Fiddle demo.
Effectively it's the same process, just with a slightly different Regular Expression.
Because there's two places in which the nodeType must be found equal to 3 and two places in which iframes are being created, I've wrapped the two indexOf() assessments inside of an if to test for the nodeType and abstracted iframe-creation to a separate function, both of which to simply avoid needless repetition.
References: