JavaScript: Create hyperlinks on the fly

Challenge: A traditional media organisation publishes various press releases daily via a central system to different channels, e.g. fax, data terminal and internet. As some special reasons, the system is not able to markup the content for the internet version. It can only change the line break to <br> and consecutive spaces to &nbsp; i.e. No hyperlinks even if there are any URLs or e-mail addresses written in the articles. It is definitely not user-friendly for internet readers and something should be made in order to improve usability.

No way to intervene the publication system but it is able to add post-publishing logic to the external JavaScript file included in the HTML output.

I decide to solve it by JavaScript regex but badly my regex sux! Theoretically it can be done by two lines of regex replace code (one for URLs and another for e-mail addresses) but they crash when replace globally at the same time. (e.g. ‘chiunam.net’ of ‘no-reply@chiunam.net’ - MY REGEX SUX!)

Finally I made it by scanning the article from start and create hyperlink for matched pattern once. It is clumsy but it works pretty good.

See my code in action.CT

Related Entries:


About this entry