I am currently using this function to add links to urls in some text:
public static String makeLinksInText(String text) {
String url, urltext = "";
int urlstart, urlend;
int i = 0;
while(i < text.length() - 5) {
if(text.substring(i, i + 4).toLowerCase().equals("http")) {
urlstart = i;
if(text.indexOf(" ", urlstart) > -1)
urlend = text.indexOf(" ", urlstart);
else if(text.indexOf(".", urlstart) > -1)
urlend = text.indexOf(".", urlstart);
else
urlend = text.length();
url = text.substring(urlstart, urlend);
urltext = text.substring(0, urlstart) + "<a href=\"" + url + "\" target=\"_blank\" style=\"font-size:10px;\">" + url + "</a>" + text.substring(urlend);
}
i++;
}
return urltext;
}
But maybe it would be better to replace using regular expressions. Can someone advice and perhaps suggest another method? Thanks
A few things to note regarding your code: (1) if ‘http’ appears as part of a text string (e.g. abdhttpac), you’ll extract/substitute something incorrectly; (2) pretty much all url’s will have a dot in them – and your searching for a dot as the end of the url is inherently wrong: think http://www.domain.com – your code will only extract ‘http://www’ and replace it.
Regex could be a better idea. You can use regex of type:
and use
$0for your actual URL for the replacement.This should catch http and https url’s. If you want other ones (e.g. ftp, gopher, etc.), you can modify the expression accordingly. Note that this would only catch properly formatted (url-encoded) URLs. Many browsers would understand URLs with quotes in them, however it is not considered proper formatting.