How to automatically convert a url to a hyperlink when it is pasted


When I tried to paste an url in the text box like 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; 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=""></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></span><br><br><a href=""></a><br><br><br><span>This would save us a lot time in task building, reviewing and creating messages.</span>

Test URL's
        <a href=''></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?


This will work:

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

JSFiddle here and Regexr