Using JavaScript to find links within plain text
Today I was working on adding the Wayne State University Twitter feed to our website. It’s not a terribly difficult task since Twitter has some auto-generated code (javascript and HTML) for adding your public time line to a website. We, however, wanted more. Twitter’s auto-generated code offers a pretty basic setup, no frills at all. Our issue with the Twitter code is that the links within tweets lack markup and are non-functioning within a web browser.
The Solution
The solution is pretty simple, but not easily found online so I wrote my own. Twitter provides you with links to two JavaScript files within their auto-generated code. The first included javascript file provides you with two functions. One is the callback function that is used to display the json feed using HTML. The second function is used to convert the time stamp to relative time to keep with Twitter look. Rather than continuing to use the include from twitter.com I localized the two functions so I could edit the callback function and get some markup around those links.
My changes are fairly simplistic and make use of regular expressions to replace obvious plain text links with a marked up version of the links so the end users will be able to click the links.
The code to replace plain text URLs with their marked up version:
var tweet = "Some tweek with a link to a site: http://wcs.wayne.edu/"; var pattern = /(HTTP:\/\/|HTTPS:\/\/)([a-zA-Z0-9.\/&?_=!*,\(\)+-]+)/i; var replace = "<a href=\"$1$2\">$1$2</a>"; tweet = tweet.replace(pattern , replace);
Now my regular expression skills are far from great, so it’s likely this can be optimized. It’s also possible I forgot some URL safe characters within the pattern. This code basically searches the tweet for anything that looks like http://i-am-a.link/cool/link.ext?okay=yes&fine or whatever the link might look like. I think it could be expanded to search for links that do not include the http:// as well, but I didn’t have a need to do that at this time. Here is the full modified twitter JavaScript code incase you want it.
The result is tweets with working links on http://wayne.edu/current/.
