Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find link in a text using jquery?

Lets say I have a text such as this "This is a long text. It contains 150 characters. You can find more about this text on this link http://www.somewebsite.com/RDFCCSDVDS".

So in above text I want to find that link and convert it into a link so that when user clicks on it, the user will be taken directly to this website.

How can I achieve this goal?

like image 775
doforumda Avatar asked Dec 05 '25 10:12

doforumda


2 Answers

Use regular expressions:

$('p').html(function(i, text) {
     return text.replace(
         /\bhttp:\/\/([\w\.-]+\.)+[a-z]{2,}\/.+\b/gi,
         '<a href="$&">$&</a>'
     );
});

demo

like image 162
Eric Avatar answered Dec 07 '25 22:12

Eric


I suspect that I could much improve upon this, though at the minute this is the best I can offer (albeit I think that some kind of replace might work more efficiently):

var $words = $('p').text().split(' ');
for (i in $words) {
    if ($words[i].indexOf('http://') == 0) {
        $words[i] = '<a href="' + $words[i] + '">' + $words[i] + '</a>';
    }
}

$('p').html($words.join(' '));

JS Fiddle demo.

A slightly improved version of the above (but good lord, it's ugly...):

var punctuation = ['!',"'",'"',',','.'];
$('p').each(
    function(){
        $words = $(this).text().split(' ');
        for (i in $words){
            if ($.inArray($words[i].charAt(0),punctuation) > -1 && $words[i].indexOf('http://') == 1){
                alert($words[i]);
            }
            else if ($.inArray($words[i].charAt($words[i].length - 1),punctuation) > -1 && ($words[i].indexOf('http://') == 1 || $words[i].indexOf('http://') == 0)){
                $words[i] = '<a href="'+$words[i].substring(0,$words[i].length-1)+'">' + $words[i].substring(0,$words[i].length-1) + '</a>' + $words[i].charAt($words[i].length-1);
            }
            else if ($words[i].indexOf('http://') == 0){
                $words[i] = '<a href="' + $words[i] + '">' + $words[i] + '</a>';
            }
        }
        $(this).html($words.join(' '));
    });

JS Fiddle demo.

I'm not quite sure what to do about quoted links, though (text such as "http://google.com", for example); and, honestly, I think that regex is probably the far, far better approach to this problem.

like image 44
David Thomas Avatar answered Dec 08 '25 00:12

David Thomas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!