Java : replacing text URL with clickable HTML link

前端 未结 6 773
不知归路
不知归路 2020-12-20 13:54

I am trying to do some stuff with replacing String containing some URL to a browser compatible linked URL.

My initial String looks like this :

\"hell         


        
6条回答
  •  心在旅途
    2020-12-20 14:21

    public static String textToHtmlConvertingURLsToLinks(String text) {
        if (text == null) {
            return text;
        }
    
        String escapedText = HtmlUtils.htmlEscape(text);
    
        return escapedText.replaceAll("(\\A|\\s)((http|https|ftp|mailto):\\S+)(\\s|\\z)",
            "$1$2$4");
    }
    

    There may be better REGEXs out there, but this does the trick as long as there is white space after the end of the URL or the URL is at the end of the text. This particular implementation also uses org.springframework.web.util.HtmlUtils to escape any other HTML that may have been entered.

提交回复
热议问题