Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find if a text contains url string

Tags:

javascript

How can I find if text contains a url string. I mean if I have

Sometexthttp://daasddas some text

I want http://daasddas to be achored or maked as a link wit javascript

like image 825
alebash Avatar asked Jul 15 '11 13:07

alebash


2 Answers

    function replaceURLWithHTMLLinks(text)
    {
      var exp = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig;
      return text.replace(exp,"<a href='$1'>$1</a>"); 
    }
like image 68
Igor Hrcek Avatar answered Oct 22 '22 11:10

Igor Hrcek


While the code above works good if all given URLs are full (http://mydomain.com), I had problems parsing a URL like:

www.mydomain.com

i.e. without a protocol. So I added some simple code to the function:

var exp = /(\b(((https?|ftp|file|):\/\/)|www[.])[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig;
var temp = text.replace(exp,"<a href=\"$1\" target=\"_blank\">$1</a>");
var result = "";

while (temp.length > 0) {
    var pos = temp.indexOf("href=\"");
    if (pos == -1) {
        result += temp;
        break;
    }
    result += temp.substring(0, pos + 6);

    temp = temp.substring(pos + 6, temp.length);
    if ((temp.indexOf("://") > 8) || (temp.indexOf("://") == -1)) {
        result += "http://";
    }
}

return result;

If someone should fine a more optimal solution to add a default protocol to URLs, let me know!

like image 35
Stephan Avatar answered Oct 22 '22 10:10

Stephan