简体   繁体   中英

Detect a hyperlink in a text - jQuery

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.

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 )

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

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM