Peter Stuart
Peter Stuart

Reputation: 2434

How do I automatically wrap text URLs in anchor tags?

I have a simple CMS I built for a client of mine.

This issue is, instead of him posting links probably through anchor tags, he just copies and pastes it straight into the text editor.

Is there a way that these links can be wrapped in an anchor tag using JavaScript? So when the page loads instead of it looking link this:

http://google.com

It will look like this

<a href="http://google.com" target="_blank">http://google.com</a>

Stack Overflow actually does this when a user posts a URL to an answer/question (if that helps understand what I am trying to achieve).

Upvotes: 4

Views: 4880

Answers (1)

struthersneil
struthersneil

Reputation: 2750

You could try something along these lines. Decorate the tags where you want these replacements to take effect with a custom attribute like data-linkify:

<div data-linkify>something http://google.com something</div><div linkify>something</div>

Now perform replacements inside any element with data-linkify set.

$('*[data-linkify]').each(function() { 
  $(this).html($(this).html().replace(/(?:(https?\:\/\/[^\s]+))/m, '<a href="$1">$1</a>'));
});

There are some caveats. This isn’t a great regex at all — it simply matches anything starting with http:// or https:// up until the first whitespace character. Look for a better URL matching regex.

Also, the use of replace against .html() means that it will break any existing links that happen to fall under your data-linkify elements! If there happen to be doublequote characters in your textual links, it will create broken anchor elements.

You might consider a very simple markup of some sort to identify links — it would be much better than guessing.

Upvotes: 5

Related Questions