Mark Needham

Thoughts on Software Development

Javascript: Using 'replace' to make a link clickable

with 2 comments

I've been doing a bit more work on my twitter application over the weekend – this time taking the tweets that I've stored in CouchDB and displaying them on a web page.

One of the problems I had is that the text of the tweets is just plain text so if there is a link in a tweet then when I display it on a web page it isn't clickable since it isn't enclosed by the '<a href"…"></a>' tag.

Javascript has a 'replace' function which you can call to allow you to replace some characters in a string with some other characters.

What I actually wanted to do was surround some characters with the link tag but most of the examples I came across didn't explain how to do this.

Luckily I came across a forum post from a few years ago which explained how to do it.

In this case then we would make use of a matching group on links to create a clickable link:

"Interesting post... Kanban &amp; estimates http://tinyurl.com/p58o3r".replace(/(http:\/\/\S+)/g, "<a href='$1'>$1</a>");

Which results in a tweet with a nice clickable link:

"Interesting post... Kanban &amp; estimates <a href='http://tinyurl.com/p58o3r'>http://tinyurl.com/p58o3r</a>"
Share and Enjoy:
  • Digg
  • del.icio.us
  • Facebook
  • HackerNews
  • StumbleUpon
  • Twitter

Written by Mark Needham

June 8th, 2009 at 11:57 am

Posted in Javascript

Tagged with

2 Responses to 'Javascript: Using 'replace' to make a link clickable'

Subscribe to comments with RSS or TrackBack to 'Javascript: Using 'replace' to make a link clickable'.

  1. There's a more complete example on Stack Overflow: http://stackoverflow.com/questions/37684/replace-url-with-html-links-javascript

    Mwanji Ezana

    8 Jun 09 at 8:54 pm

  2. Regex. Is there anything it can't do? ;-)

    Adam Scott

    9 Jun 09 at 5:59 am

Leave a Reply