如何在粘贴时自动将URL转换为超链接

时间:2014-06-11 12:14:47

标签: javascript jquery html jquery-plugins

当我尝试在https://stackoverflow.com/这样的文本框中粘贴网址时,它不会自动转换为超链接。

我尝试使用正则表达式,这是我之前询问过的Question。我在这个问题中使用的功能很好,但实际上它将取代所有链接,包括标签中的链接(IMG,现有的A HREF)。

我不想使用regx ,如果我点击任何提交或保存按钮时使用regx转换。

**当用户在文本框中粘贴网址时,它会自动将任何链接转换为超链接****

我已尝试使用regx

例如:

what = "<span>In the task system, is there a way to automatically have any site / page URL or image URL be hyperlinked in a new window?</span><br><br><span>So If I type or copy http://www.stackoverflow.com/&nbsp; for example anywhere in the description, in any of the internal messages or messages to clients, it automatically is a hyperlink in a new window.</span><br><a href="http://www.stackoverflow.com/">http://www.stackoverflow.com/</a><br>    <br><span>Or if I input an image URL anywhere in support description, internal messages or messages to cleints, it automatically is a hyperlink in a new window:</span><br> <span>https://static.doubleclick.net/viewad/4327673/1-728x90.jpg</span><br><br><a href="https://static.doubleclick.net/viewad/4327673/1-728x90.jpg">https://static.doubleclick.net/viewad/4327673/1-728x90.jpg</a><br><br><br><span>This would save us a lot time in task building, reviewing and creating messages.</span>



Test URL's
        http://www.stackoverflow.com/
        https://stackoverflow.com/
        https://stackoverflow.com/
        www.stackoverflow.com
        //stackoverflow.com/
        <a href='https://stackoverflow.com/'>https://stackoverflow.com/</a>";

我已尝试过此代码

function Linkify(what) {
    str = what; out = ""; url = ""; i = 0;
    do {
        url = str.match(/((https?:\/\/)?([a-z\-]+\.)*[\-\w]+(\.[a-z]{2,4})+(\/[\w\_\-\?\=\&\.]*)*(?![a-z]))/i);
        if(url!=null) {
            // get href value
            href = url[0];
            if(href.substr(0,7)!="http://") href = "http://"+href;

            // where the match occured
            where = str.indexOf(url[0]);

            // add it to the output
            out += str.substr(0,where);

            // link it
            out += '<a href="'+href+'" target="_blank">'+url[0]+'</a>';

            // prepare str for next round
            str = str.substr((where+url[0].length));
        } else {
            out += str;
            str = "";
        }
    } while(str.length>0);
    return out;
}

fiddle无法正常工作

当我们将文件框中的网址粘贴到文本框中时,是否可以自动将其转换为我可以有一些示例吗?

感谢。

4 个答案:

答案 0 :(得分:5)

这将有效:

var newStr = str.replace(/(<a href=")?((https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,6}\b([-a-zA-Z0-9@:%_\+.~#?&//=]*)))(">(.*)<\/a>)?/gi, function () {
    return '<a href="' + arguments[2] + '">' + (arguments[7] || arguments[2]) + '</a>'
});

JSFiddle hereRegexr

答案 1 :(得分:3)

Autolink URL in ContentEditable Iframe

在这个问题中我回答了

这样当用户在richtextbox中粘贴网址时,它会自动将任何链接转换为超链接 - 这里我的richtextbox不是div,而是iframe

如果您是div或其他任何人,您可以从这两个问题中得到答案

Autolink URL in contenteditable jQuery: Convert text URL to link as typing

这里是代码

autoAppLink: function (Iframe) {
    var saveSelection, restoreSelection;

    if (window.getSelection && document.createRange) {
        saveSelection = function (containerEl) {
            var range = iframe[0].contentWindow.getSelection().getRangeAt(0);
            var preSelectionRange = range.cloneRange();
            preSelectionRange.selectNodeContents(containerEl);
            preSelectionRange.setEnd(range.startContainer, range.startOffset);
            var start = preSelectionRange.toString().length;

            return {
                start: start,
                end: start + range.toString().length
            }
        };

        restoreSelection = function (containerEl, savedSel) {
            var charIndex = 0, range = document.createRange();
            range.setStart(containerEl, 0);
            range.collapse(true);
            var nodeStack = [containerEl], node, foundStart = false, stop = false;

            while (!stop && (node = nodeStack.pop())) {
                if (node.nodeType == 3) {
                    var nextCharIndex = charIndex + node.length;
                    if (!foundStart && savedSel.start >= charIndex && savedSel.start <= nextCharIndex) {
                        range.setStart(node, savedSel.start - charIndex);
                        foundStart = true;
                    }
                    if (foundStart && savedSel.end >= charIndex && savedSel.end <= nextCharIndex) {
                        range.setEnd(node, savedSel.end - charIndex);
                        stop = true;
                    }
                    charIndex = nextCharIndex;
                } else {
                    var i = node.childNodes.length;
                    while (i--) {
                        nodeStack.push(node.childNodes[i]);
                    }
                }
            }

            var sel = iframe[0].contentWindow.getSelection();
            sel.removeAllRanges();
            sel.addRange(range);
        }
    } else if (document.selection) {
        saveSelection = function (containerEl) {
            var selectedTextRange = document.selection.createRange();
            var preSelectionTextRange = document.body.createTextRange();
            preSelectionTextRange.moveToElementText(containerEl);
            preSelectionTextRange.setEndPoint("EndToStart", selectedTextRange);
            var start = preSelectionTextRange.text.length;

            return {
                start: start,
                end: start + selectedTextRange.text.length
            }
        };

        restoreSelection = function (containerEl, savedSel) {
            var textRange = document.body.createTextRange();
            textRange.moveToElementText(containerEl);
            textRange.collapse(true);
            textRange.moveEnd("character", savedSel.end);
            textRange.moveStart("character", savedSel.start);
            textRange.select();
        };
    }

    function createLink(matchedTextNode) {
        var el = document.createElement("a");
        el.href = matchedTextNode.data;
        el.target = "_blank";
        el.appendChild(matchedTextNode);
        return el;
    }

    function shouldLinkifyContents(el) {
        return el.tagName != "A";
    }

    function surroundInElement(el, regex, surrounderCreateFunc, shouldSurroundFunc) {
        var child = el.lastChild;
        while (child) {
            if (child.nodeType == 1 && shouldSurroundFunc(el)) {
                surroundInElement(child, regex, createLink, shouldSurroundFunc);
            } else if (child.nodeType == 3) {
                surroundMatchingText(child, regex, surrounderCreateFunc);
            }
            child = child.previousSibling;
        }
    }

    function surroundMatchingText(textNode, regex, surrounderCreateFunc) {
        var parent = textNode.parentNode;
        var result, surroundingNode, matchedTextNode, matchLength, matchedText;
        while (textNode && (result = regex.exec(textNode.data))) {
            matchedTextNode = textNode.splitText(result.index);
            matchedText = result[0];
            matchLength = matchedText.length;
            textNode = (matchedTextNode.length > matchLength) ?
                matchedTextNode.splitText(matchLength) : null;
            surroundingNode = surrounderCreateFunc(matchedTextNode.cloneNode(true));
            parent.insertBefore(surroundingNode, matchedTextNode);
            parent.removeChild(matchedTextNode);
        }
    }

    var iframe = Iframe,
        textbox = iframe.contents().find("body")[0];
    var urlRegex = /http(s?):\/\/($|[^ ]+)/;

    function updateLinks() {
        var savedSelection = saveSelection(textbox);
        surroundInElement(textbox, urlRegex, createLink, shouldLinkifyContents);
        restoreSelection(textbox, savedSelection);
    }

    var $textbox = $(textbox);


    $textbox.focus();

    var keyTimer = null, keyDelay = 1000;

    $textbox.keyup(function () {
        if (keyTimer) {
            window.clearTimeout(keyTimer);
        }
        keyTimer = window.setTimeout(function () {

            updateLinks();
            keyTimer = null;
        }, keyDelay);
    });

}

答案 2 :(得分:0)

这是一个建议:

function convertLinks(text) {

    var link = text.match(/(?:www|https?)[^\s]+/g),
        aLink = [],
        replacedText = text;

    if (link != null) {

      for (i=0;i<link.length;i++) {
        var replace;
        if (!( link[i].match(/(http(s?))\:\/\//) ) ) { replace = 'http://' + link[i]; } else { replace = link[i] };
        var linkText = replace.split('/')[2];
        if (linkText.substring(0,3) == "www") { linkText = linkText.replace('www.','') };
        aLink.push('<a href="' + replace + '" target="_blank">' + linkText + '</a>');
        replacedText = replacedText.split(link[i]).join(aLink[i]);
      }

      return repText

    } else {
      return text
    }
  }

我也here发布了此帖子

答案 3 :(得分:0)

对于在 2021 年发现这个问题并希望有一个很好的功能来完成所有工作的人,这是我在此 blog post 上找到的一个:

function linkify(inputText) {
    var replacedText, replacePattern1, replacePattern2, replacePattern3;

    //URLs starting with http://, https://, or ftp://
    replacePattern1 = /(\b(https?|ftp):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/gim;
    replacedText = inputText.replace(replacePattern1, '<a href="$1" target="_blank">$1</a>');

    //URLs starting with "www." (without // before it, or it'd re-link the ones done above).
    replacePattern2 = /(^|[^\/])(www\.[\S]+(\b|$))/gim;
    replacedText = replacedText.replace(replacePattern2, '$1<a href="http://$2" target="_blank">$2</a>');

    //Change email addresses to mailto:: links.
    replacePattern3 = /(([a-zA-Z0-9\-\_\.])+@[a-zA-Z\_]+?(\.[a-zA-Z]{2,6})+)/gim;
    replacedText = replacedText.replace(replacePattern3, '<a href="mailto:$1">$1</a>');

    return replacedText;
}