【问题标题】:regex not detecting youtube links in javascript contenteditable div正则表达式未检测到 javascript contenteditable div 中的 youtube 链接
【发布时间】:2013-08-15 20:30:58
【问题描述】:

我正在使用这个脚本来检测粘贴到 contenteditable div 中的 youtube URL 并替换为可嵌入代码。

这在粘贴纯文本 youtube URL 时有效,但它不会检测或替换作为可点击链接粘贴的 URL。

如何修改代码以替换纯文本 youtube 链接和粘贴的可点击链接?

$.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, '&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 && !/^(a|button|textarea)$/i.test(n.tagName))
        {
            $.Redactor.fn.formatLinkify.call(n, protocol, convertLinks, convertImageLinks, convertVideoLinks);
        }
    }
};

【问题讨论】:

  • 如果您发布一个演示问题的小提琴,您可能会收到更多回复。
  • 你能举例说明什么是匹配的和不匹配的吗?

标签: javascript jquery regex youtube contenteditable


【解决方案1】:

由于您在此行的递归调用中排除了锚点(&lt;a&gt; 标记),因此未处理任何链接:

else if (n.nodeType === 1 && !/^(a|button|textarea)$/i.test(n.tagName))

您应该通过将正则表达式更改为来允许它们

/^(button|textarea)$/i

或使用其他一些条件来确保处理链接(或其href 属性)。

例如,如果您遇到一个链接,您可以根据urlYoutube regEx 测试其href 属性。

查看jsFiddle了解更多详情。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-04-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多