How to add an anchor tag to a URL in a String

Markus Freundorfer

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.

billyonecan

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

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

From Dev

How to add an active class to an anchor tag based on URL and Vanity URLs?

From Dev

How to check if a string is an anchor tag?

From Dev

How to check if a string is an anchor tag?

From Dev

How to find anchor tag in div and add class?

From Dev

How to add class to particular li with anchor tag?

From Dev

How to parse URL from anchor tag

From Dev

How to change html anchor tag query string

From Dev

How to add a class to the image tag within anchor tag on hover?

From Dev

Decoding Anchor Tag in String

From Dev

how to add anchor to django url in template

From Dev

How to add data to the anchor tag in HTML and access it using jQuery?

From Dev

How to add a h3 and p to an anchor tag

From Dev

HTML: how to add anchor tag without effecting visual display?

From Dev

How to add Anchor tag on every database entery using codeigniter

From Dev

How to hide a div if the url of anchor tag is empty using jquery

From Dev

How to create anchor tag

From Dev

Hiding a Anchor Tag with a specific url

From Dev

Add string to end of URL in iframe tag

From Dev

how to disable anchor tag in jquery?

From Dev

How to replicate an anchor tag in Excel

From Dev

How to use an anchor tag with jQuery

From Dev

How to pass variable in anchor tag

From Dev

how to trigger an anchor tag resides on the page by clicking on another anchor tag

From Dev

how to trigger an anchor tag resides on the page by clicking on another anchor tag

From Dev

Add value of input field to anchor/link tag

From Dev

Using anchor tag to link to an external URL in Java

From Dev

Check URL if it has a specific anchor tag

From Dev

Post url is not coming in anchor href tag

From Dev

Remove only anchor tag from string

Related Related

HotTag

Archive