URLs to Hyperlinks Regex

As a follow on to the Email Mailto Links Regex article, this article gives an example of a PeopleCode function that searches for URLs (web addresses) in a text string and converts them into HTML hyperlinks.

So for example the text:

http://www.peoplesoftwiki.com

Is replaced with the HTML:

<a href="http://www.peoplesoftwiki.com" target="_blank">http://www.peoplesoftwiki.com</a>

This allows a end user to click on the hyperlink and have it open in a new window. This is particularly useful for long description configuration fields where users can specify a URL and this will automatically displayed as a hyperlink. Note that this would require the use of a HTML area to display the hyperlink correctly.

This is the PeopleCode function:

Function ConvertURLsToHyperLinks(&sInput As string) Returns string
 
   Local JavaObject &jURLRegex, &jURLLinkRegex, &jInput;
   Local string &sHTML;
 
   /* Match any URLs */
   &jURLRegex = CreateJavaObject("java.lang.String", "\bhttps?://\S+\b");
 
   /* Replace the found match ($0 back reference) and enclose with a href HTML tag */
   &jURLLinkRegex = CreateJavaObject("java.lang.String", "<a href=""$0"" target=""_blank"">$0</a>");
 
   /* Store the text to be scanned for URLs as a Java string object */
   &jInput = CreateJavaObject("java.lang.String", &sInput);
 
   /* Perform a replace all using the search URL regex and the URL link regex */
   &sHTML = &jInput.replaceAll(&jURLRegex, &jURLLinkRegex);
 
   Return &sHTML;
 
End-Function;

A few limitations to be aware of with this function are:

  • The URL must start with http(s):// (either http or https protocol)
  • If you have a trailing slash at the end of your URL it will not be matched. Leave it out
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License