2

I've got a few strings which contain youtube links (different lenghts and positions in the string, not every string contains an URL) and text. These strings will be written into paragraph-tags but i want the URLs to be clickable, so i need anchor tags around the URL.

I managed to find a way to access the paragraph which contains a link:

if($("#facebookFeed p:contains('http')").length){
    //do stuff
}

I'm stuck here and not sure if thats the right way to do it.

  • For starters, there's no such thing as a perfect URL regex, but you can plug in a 'pretty good' one that will pick out URL's more reliably – darkpbj Feb 18 '14 at 15:07
  • 2
    @darkpbj Speaking of "the perfect URL regex", I've liked using this - http://mathiasbynens.be/demo/url-regex – admdrew Feb 18 '14 at 15:11

2 Answers2

3

You'd have to use regex to match the URLs within the string, and then wrap them in an anchor:

$('p:contains("http://")').html(function(index, html) {
    var url = html.match(/(((ftp|https?):\/\/)[\-\w@:%_\+.~#?,&\/\/=]+)|((mailto:)?[_.\w-]+@([\w][\w\-]+\.)+[a-zA-Z]{2,3})/g);

    $.each(url, function(i, v) {
        html = html.replace(v, '<a href="' + v + '">' + v + '</a>');        
    });

    return html;
});

The example above uses the regex pattern found in this answer

Here's a fiddle

Community
  • 1
  • 1
billyonecan
  • 20,090
  • 8
  • 42
  • 64
  • Out of curiosity, why are you testing for `ftp`? I didn't think anchors would work for them. – admdrew Feb 18 '14 at 15:44
  • 1
    @admdrew I used a regex pattern found in another answer (lazy I know), I just wanted to demonstrate how to replace the matches with anchors. – billyonecan Feb 18 '14 at 15:46
  • Please edit so that 'var url = html.match(/(((ftp|https?):\/\/)[\-\w@:%_\+.~#?,&\/\/=]+)|((mailto:)?[_.\w-]+@([\w][\w\-]+\.)+[a-zA-Z]{2,3})/g) || []' so url would never be null but instead a blank array. An error pops up whenever the html var does not contain any valid url's. – neilmarion Aug 26 '14 at 16:29
1

The following will do

$("#facebookFeed p:contains('http')").each(function() {
    $(this).wrapInner('<a href="' + $(this).text() + '"/>');
});

As demonstrated here: http://jsfiddle.net/uyHQ2/

Ofcourse, this assumes a certain HTML layout. If yours is different, then please post an example of the HTML.

Martijn
  • 3,696
  • 2
  • 38
  • 64