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

5

6

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.

Painter answered 11/6, 2014 at 12:14 Comment(5)
You should post, what you have tried first..! {CODE}Staley
@RajaprabhuAravindasamy i tried using regular expression in this question #23759802 i mentioned that in the question abovePainter
@ZiNNED paste an url in the text boxPainter
@Painter Show the code that you have used while making an attempt. so that we could inherit that code and expel a possible solution for you.. Are you getting what i am trying to say...?Staley
@RajaprabhuAravindasamy the link i gave is my question i asked before that's why i have not given any sample now i updated the question please checkPainter
P
3

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

}
Painter answered 20/6, 2014 at 6:35 Comment(0)
O
7

This will work:

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 here and Regexr

Otherworldly answered 11/6, 2014 at 12:44 Comment(8)
Vinz243 really thanks if this works i am really thankful to youPainter
Vinz243 see this fiddle this dosent work with regexp i want to convert it automatically when i paste a urlPainter
Open you broser console and you will realize that you forgot to include jQuery...Otherworldly
this is not working try http://foo.co.uk/ http://regexr.com/foo.html?q=bar <a href="http://foo.co.uk/">no</a> <a href="http://regexr.com/foo.html?q=bar">yes</a> with your regxPainter
that's not finding even a single url if i place http://regexr.com/foo.html?q=bar in fiddle and run thats not linkingPainter
Yes it does for me. Please link itOtherworldly
$('div').html(newStr) means it must be placed in a div. In a real life app it should even have an id.Otherworldly
ahh im sorry but this works in fiddle in my code that fails :(Painter
P
4

For anyone finding this question in 2021 and looking to have a nice function to do it all, here's one I found on this 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;
}
Paulo answered 9/2, 2021 at 21:50 Comment(0)
P
3

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

}
Painter answered 20/6, 2014 at 6:35 Comment(0)
S
3

Here is my answer (improved Version including video links).

See also this Codepen here.

const convertLinks = ( input ) => {

  let text = input;
  const linksFound = text.match( /(?:www|https?)[^\s]+/g );
  const aLink = [];

  if ( linksFound != null ) {

    for ( let i=0; i<linksFound.length; i++ ) {
      let replace = linksFound[i];
      if ( !( linksFound[i].match( /(http(s?)):\/\// ) ) ) { replace = 'http://' + linksFound[i] }
      let linkText = replace.split( '/' )[2];
      if ( linkText.substring( 0, 3 ) == 'www' ) { linkText = linkText.replace( 'www.', '' ) }
      if ( linkText.match( /youtu/ ) ) {

        let youtubeID = replace.split( '/' ).slice(-1)[0];
        aLink.push( '<div class="video-wrapper"><iframe src="https://www.youtube.com/embed/' + youtubeID + '" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe></div>' )
      }
      else if ( linkText.match( /vimeo/ ) ) {
        let vimeoID = replace.split( '/' ).slice(-1)[0];
        aLink.push( '<div class="video-wrapper"><iframe src="https://player.vimeo.com/video/' + vimeoID + '" frameborder="0" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe></div>' )
      }
      else {
        aLink.push( '<a href="' + replace + '" target="_blank">' + linkText + '</a>' );
      }
      text = text.split( linksFound[i] ).map(item => { return aLink[i].includes('iframe') ? item.trim() : item } ).join( aLink[i] );
    }
    return text;

  }
  else {
    return input;
  }
}

this replaces long and clumsy links within plain texts to short clickable links within that text. (And also wraps videos in responsive iframes)

Example:

This clumsy link https://mcmap.net/q/847586/-convert-plain-text-links-to-clickable-links/52544985#52544985 is very clumsy and this http://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split is not much better. This one www.apple.com is nice but www could be omitted

Becomes:

This clumsy link <a href="https://mcmap.net/q/847586/-convert-plain-text-links-to-clickable-links/52544985#52544985" target="_blank">stackoverflow.com</a> is very clumsy and this <a href="http://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split" target="_blank">developer.mozilla.org</a> is not much better. This one <a href="http://www.apple.com" target="_blank">apple.com</a> is nice but www could be omitted

Is displayed as:

This clumsy link stackoverflow.com is very clumsy and this developer.mozilla.org is not much better. This one apple.com is nice but www can be removed

Senary answered 27/9, 2018 at 21:14 Comment(0)
C
0

for js folks, you can use a library: https://www.npmjs.com/package/autolinker

var autolinker = new Autolinker( {
    newWindow : false,
    truncate  : 30
} );

var html = autolinker.link( "Joe went to www.yahoo.com" );
// produces: 'Joe went to <a href="http://www.yahoo.com">yahoo.com</a>'
Commensurable answered 12/6, 2022 at 17:21 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.