Recently I came across a problem, I needed to convert a plain text string, that could possibly have a URL in it, to a string with clickable URLs. This is possible with the right JavaScript code. You could always do this on the server-side with PHP or another language, but I didn’t want to throw more text into my database. So I searched and pieced together some code to take a plain text string and covert it to a clickable link with JavaScript. I created a simple function that takes a parameter of a string and searches for a valid URL (with a regular expression) within it.
script.js
|
|
function convertToLinks(text) { var replaceText, replacePattern1; //URLs starting with http://, https:// replacePattern1 = /(\b(https?):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig; replacedText = text.replace(replacePattern1, '<a class="colored-link-1" title="$1" href="$1" target="_blank">$1</a>'); //URLs starting with "www." replacePattern2 = /(^|[^\/])(www\.[\S]+(\b|$))/gim; replacedText = replacedText.replace(replacePattern2, '$1<a class="colored-link-1" href="http://$2" target="_blank">$2</a>'); //returns the text result return replacedText; } |
All you have to do is call this function with a string as the parameter and it will return the new string with links. If you wanted to search for more links, it would be as easy as creating another regular expression and parsing through the text again before returning it.
Here is the code you could use to call this function:
|
|
var textWithURL = "Here is a text block with a normal URL http://www.grumbleonline.com"; textWithURL = convertToLinks(textWithURL); alert(textWithURL); //output would be: //Here is a text block with a normal URL <a href="http://www.grumbleonline.com">http://www.grumbleonline.com</a> |
Here is a more complex case were http:// is left out:
|
|
var textWithURL = "Here is a text block with a short URL www.grumbleonline.com"; textWithURL = convertToLinks(textWithURL); alert(textWithURL); //output would be: //Here is a text block with a normal URL <a href="http://www.grumbleonline.com">www.grumbleonline.com</a> |
There are of course the cases where someone could put a sub domain, this would not be caught be these regular expressions.
I hope this helped, if you have any questions or comments feel free to leave them below.