regex not detecting youtube links in javascript contenteditable div
I am using this script which detects youtube URLS pasted into the
contenteditable div and replaces with the embedable code.
This works when plain text youtube URLS are pasted, but it doesn't detect
or replace URLS that are pasted as clickable links.
How can i modify the code to replace both plain text youtube links and the
clickable links that are pasted?
$.Redactor.fn.formatLinkify = function(protocol, convertLinks,
convertImageLinks, convertVideoLinks)
{
var url1 = /(^|<|\s)(www\..+?\..+?)(\s|>|$)/g,
url2 = /(^|<|\s)(((https?|ftp):\/\/|mailto:).+?)(\s|>|$)/g,
urlImage = /(https?:\/\/.*\.(?:png|jpg|jpeg|gif))/gi,
urlYoutube =
/.*(youtu.be\/|v\/|u\/\w\/|embed\/|watch\?v=|\&v=)([^#\&\?]*).*/;
var childNodes = (this.$editor ? this.$editor.get(0) :
this).childNodes, i = childNodes.length;
while (i--)
{
var n = childNodes[i];
if (n.nodeType === 3)
{
var html = n.nodeValue;
// youtube
if (convertVideoLinks && html && html.match(urlYoutube))
{
html = html.replace(urlYoutube, '<iframe width="560"
height="315" src="//www.youtube.com/embed/$2"
frameborder="0" allowfullscreen></iframe>');
$(n).after(html).remove();
}
// image
else if (convertImageLinks && html && html.match(urlImage))
{
html = html.replace(urlImage, '<img src="$1">');
$(n).after(html).remove();
}
// link
else if (convertLinks && html && (html.match(url1) ||
html.match(url2)))
{
html = html.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(url1, '$1<a href="' + protocol + '$2">$2</a>$3')
.replace(url2, '$1<a href="$2">$2</a>$5');
$(n).after(html).remove();
}
}
else if (n.nodeType === 1 &&
!/^(a|button|textarea)$/i.test(n.tagName))
{
$.Redactor.fn.formatLinkify.call(n, protocol, convertLinks,
convertImageLinks, convertVideoLinks);
}
}
};
No comments:
Post a Comment