How to auto convert an url into a hyperlink when it is pasted

Tags: , , ,



When I tried to paste an url in the text box like https://stackoverflow.com/ it doesn’t convert to a hyperlink automatically.

i tried using regular expression this is the Question i asked before. The function that i use in this question works fine, but actually it will replace all links including links in tags (IMG, existing A HREFs).

i dont want to use regx if i use regx convertion happens when i click any submit or save button.

**When a user paste’s a url in a text box it should automatically convert any link to hyperlink****

i’ve tried this using regx

For example:

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>";

I’ve tried this code

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 that’s not working

Is it possible to convert it automatically when we paste a url in a text box like we are getting in stack over flow can I have some examples?

Thanks.

Answer

Autolink URL in ContentEditable Iframe

In this question i answered

so that when a user paste’s a url in a richtextbox it automatically converts any link to hyperlink – here my richtextbox is not a div its an iframe

if your’s is a div or any other you can get answer from these two questions

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

here’s the code

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);
    });

}


Source: stackoverflow