Javascript: Using 'replace' to make a link clickable
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 & 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 & estimates <a href='http://tinyurl.com/p58o3r'>http://tinyurl.com/p58o3r</a>"
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
Regex. Is there anything it can't do?
Adam Scott
9 Jun 09 at 5:59 am