element.contentEditable

ようわからん

HTML

<div contenteditable="true" id="content">
    http://youtu.be/w0iYoRzstJY
</div>

JavaScript

formatLinkify = function (protocol, convertLinks, convertImageLinks, convertVideoLinks) {
    var url1 = /(^|&lt;|\s)(www\..+?\..+?)(\s|&gt;|$)/g,
        url2 = /(^|&lt;|\s)(((https?|ftp):\/\/|mailto:).+?)(\s|&gt;|$)/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];
        console.log(i, n, n.nodeType);
        if (n.nodeType === 3) {
            console.log("found text node", n);
            var html = n.nodeValue;

            // youtube
            if (convertVideoLinks && html && html.match(urlYoutube)) {
                console.log("match", n);
                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, '&amp;')
                    .replace(/</g, '&lt;')
                    .replace(/>/g, '&gt;')
                    .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 && !/^(button|textarea)$/i.test(n.tagName)) {
            console.log("got a type 1 node", n);
            formatLinkify.call(n, protocol, convertLinks, convertImageLinks, convertVideoLinks);
        }
    }
};
formatLinkify.call($("#content")[0], false, false,...