Skip Navigation

Blog » Make URLs and Email Addresses Clickable Automatically with VBScript

How to make URLs and email addresses within text clickable using VBScript Regular Expressions.

VBScript Regular Expressions are, as in other languages, a very powerful tool, allowing you to find and manipulate patterns within strings easily and quickly. The syntax for them can often be a headache, but once you are familiar with them, you will find them invaluable.

One potential application for regular expressions in VBScript is to process text entered into a website via a form. Normal text replacement will allow you to filter out swear words and highlight specific phrases, but regular expressions allow you to go further. The below example demonstrates how to use them to make any valid email addresses or URLs into clickable links programmatically.

The function itself is easy to call, like so:

strTextToProcess = create_links(strTextToProcess)

The create_links function makes use of another function, also included below, called "ereg_replace". This is a simple function to make regular expression text replacement easier, and you can find out more about it in my article about VBScript Regular Expressions.

function create_links(strText) strText = " " & strText strText = ereg_replace(strText, "(^|[\n ])([\w]+?://[^ ,""\s<]*)", "$1<a href=""$2"">$2</a>") strText = ereg_replace(strText, "(^|[\n ])((www|ftp)\.[^ ,""\s<]*)", "$1<a href=""http://$2"">$2</a>") strText = ereg_replace(strText, "(^|[\n ])([a-z0-9&\-_.]+?)@([\w\-]+\.([\w\-\.]+\.)*[\w]+)", "$1<a href=""mailto:$2@$3"">$2@$3</a>") strText = right(strText, len(strText)-1) create_links = strText end function function ereg_replace(strOriginalString, strPattern, strReplacement) ' Function replaces pattern with replacement dim objRegExp : set objRegExp = new RegExp objRegExp.Pattern = strPattern objRegExp.IgnoreCase = True objRegExp.Global = True ereg_replace = objRegExp.replace(strOriginalString, strReplacement) set objRegExp = nothing end function

Finally, here is a demonstration of the above code in action:

strTextToProcess = "This simple pair of functions, from http://www.addedbytes.com, will take any text and convert valid URLs and email addresses into clickable links. Problems, feedback and suggestions should be sent to dave@addedbytes.com or posted in the comments section, which you can reach through the link below." strTextToProcess = create_links(strTextToProcess) response.write strTextToProcess

The three lines above will output:

This simple pair of functions, from http://www.addedbytes.com, will take any text and convert valid URLs and email addresses into clickable links. Problems, feedback and suggestions should be sent to dave@addedbytes.com or posted in the comments section, which you can reach through the link below.

comments powered by Disqus