To accomplish this task, the technique is the same used for Bbcode. You need to use regular expressions to identify possible Urls and replace them with filled anchors.
I created an expression to exemplify with javascript: http://rubular.com/r/btYgux8UTc
After creating the expression to isolate possible URL’s, you will use the function String.prototype.replace
to replace these with anchors, retrieving the main part for Hyper text Reference (href
).
Take 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
now contains the same value as text, but replacing URL’s 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 use gets like this:
'Acesse o www.stackoverflow.com para tirar suas dúvidas.'.URLToAnchors();
This squeeze I created should be used for the most diverse URL formats with search, URL comments, security protocol etc... In case someone has in mind to improve something please share the permanent link.
You have a text where exactly?
– Math
Javascript and Java are very different, and used in very different situations. Could you clarify in what situation you need it? On the server or client?
– bfavaretto
Iss same @bfavaretto, on front and back-end.
– user4919