1

I have a plain text, say, "Hello how are you, please visit 'http://google.com'".

I am displaying this in a div using jQuery (this text is being randomly generated). My question is, is there any way that I can detect that "http://google.com" in the text is a hyperlink and thereby convert that part of the text in to a clickable hyperlink?

Thanks.

talha2k
  • 24,937
  • 4
  • 62
  • 81
Jayesh
  • 3,891
  • 11
  • 55
  • 83
  • possible duplicate of [jQuery detect and validate an URL](http://stackoverflow.com/questions/7705501/jquery-detect-and-validate-an-url) – Felix Kling Oct 15 '11 at 08:31
  • The answer of your question is actually the following topic http://stackoverflow.com/questions/37684/how-to-replace-plain-urls-with-links – Krasimir Oct 15 '11 at 08:37

4 Answers4

3

If you are using jQuery you should check out linkify, which does it automatically for you.

$("#content").linkify();

source available here: https://code.google.com/archive/p/jquery-linkify/
and here: http://www.dave-smith.info/jquery.linkify/ (mirror at web.archive.org)

brasofilo
  • 25,496
  • 15
  • 91
  • 179
Mark Knol
  • 9,663
  • 3
  • 29
  • 44
1

This regex works for me (slightly modified version of An Improved Liberal, Accurate Regex Pattern for Matching URLs).

text = text.replace(
         /\b((?:[a-z][\w-]+:(?:\/{1,3}|[a-z0-9%])|www\d{0,3}[.]
         |[a-z0-9.-]+[.][a-z]{2,4}\/)(?:(?:[^\s()<>.]+[.]?)+|((?:[^\s()<>]+
         |(?:([^\s()<>]+)))))+(?:((?:[^\s()<>]+|(?:([^\s()<>]+))))
         |[^\s`!()[]{};:'".,<>?«»“”‘’]))/gi,
         "<a target=_blank href=$1>$1</a>");
Narendra Yadala
  • 9,554
  • 1
  • 28
  • 43
0

I know it's late. I've search anywhere to find an answer. You can try this.

var get_words = 'This is a long text. It contains 150 characters. You can find more about this text on this link http://www.somewebsite.com/RDFCCSDVDS';
$('p').html(beautify_text(get_words));

function beautify_text(text){
  var $words = text.split(' ');
  for (i in $words) {
      if ($words[i].indexOf('http://') == 0) {
          $words[i] = '<a href="' + $words[i] + '" target="_blank">' + $words[i] + '</a>';
      }
  }
  return $words.join(' ');
}
-1

You can achieve this by doing:

<?php

// The Regular Expression filter

$reg_exUrl = "/(http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/";

// The Text you want to filter for urls

$text = "Hello how are you, please visit http://google.com";

// Check if there is a url in the text

if(preg_match($reg_exUrl, $text, $url)) {

       // make the urls hyper links

       echo preg_replace($reg_exUrl, "<a href="{$url[0]}">{$url[0]}</a> ", $text);

} else {

       // if no urls in the text just return the text

       echo $text;

}
?>

Here is a complete tutorial: Find URLs in text and make links

Hope this helps.

talha2k
  • 24,937
  • 4
  • 62
  • 81