To perform this task, the technique is the same as for BBCode. You need to use regular expressions to identify possible URL's and substitutes for filled anchors.
I've created an expression to exemplify with javascript: link
Once you have created the expression to isolate the possible URL's, you will use the String.prototype.replace
function to replace these by anchors, retrieving the main part for the hyper text reference ( href
).
See an example:
var
reURL = /((?:http(s)?:\/\/)?(?:www(\d)?\.)?([\w\-]+\.\w{2,})\/?((?:\?(?:[\w\-]+(?:=[\w\-]+)?)?(?:&[\w\-]+(?:=[\w\-]+)?)?))?(#(?:[^\s]+)?)?)/g,
text = 'Acesse o www.stackoverflow.com para tirar suas dúvidas.',
html = text.replace(reURL, '<a href="http$2://www$3.$4$5$6">$1</a>');
In this case the variable html
will contain the same value as text, however replacing URLs with anchors.
You can also create a function to make it more efficient:
String.prototype.URLToAnchors = function() {
return this.replace(/((?:http(s)?:\/\/)?(?:www(\d)?\.)?([\w\-]+\.\w{2,})\/?((?:\?(?:[\w\-]+(?:=[\w\-]+)?)?(?:&[\w\-]+(?:=[\w\-]+)?)?))?(#(?:[^\s]+)?)?)/g, '<a href="http$2://www$3.$4$5">$1</a>');
}
The usage looks like this:
'Acesse o www.stackoverflow.com para tirar suas dúvidas.'.URLToAnchors();
10.04.2014 / 19:39