Question

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.

Était-ce utile?

La solution

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

Autres conseils

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.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top