JAVA代码javascript
项目的一个需求,给用户提交的内容中的网址添加上连接,PC端用的是jsp,因此用了taglib,用起来更加方便,关键代码:java
Pattern p = Pattern.compile("(https?://|www\\.)[a-zA-Z_0-9\\-@]+(\\.\\w[a-zA-Z_0-9\\-:]+)+(/[()~#&\\-=?\\+\\%/\\.\\w]+)?"); Matcher m = p.matcher(content); StringBuffer sb = new StringBuffer(); while (m.find()) { String url = m.group(); String href = url; if (!url.startsWith("http") && !url.startsWith("https")) { href = "http://" + url; } m.appendReplacement(sb, "<a target=\"_blank\" href=\"" + href + "\">" + url + "</a>"); } m.appendTail(sb);
其中content是传进来的参数。Matcher类的appendReplacement方法的做用是将当前匹配子串替换为指定字符串,而且将替换后的子串以及其以前到上次匹配子串以后的字符串段添加到一个 StringBuffer 对象里,再用appendTail方法将最后剩余的内容添加到sb对象中,获得一个所有替换后的字符串。react
JS代码app
项目的移动端用的是reactjs,客户端渲染,因此采用了js来替换内容,关键代码:jsp
var convertUrl = function(content) { if (!content) { return ""; } let urlPattern = /(https?:\/\/|www\.)[a-zA-Z_0-9\-@]+(\.\w[a-zA-Z_0-9\-:]+)+(\/[\(\)~#&\-=?\+\%/\.\w]+)?/g; content = content.replace(urlPattern, function (match) { var href = match; if (match.indexOf("http") == -1) { href = "http://" + match; } return "<a target=\"_blank\" href=\"" + href + "\">" + match + "</a>"; }); return content; }
js里面用了replace方法,可是第二个参数没有用要替换的字符串,而是用了一个方法,方法的参数是匹配到的子串,在global模式下逐个替换。url
不多用到replace方法第二个参数是方法的,用法参考mdn的String.prototype.replace() 。prototype