문제

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.

도움이 되었습니까?

해결책

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

다른 팁

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top