2 回答
![?](http://img1.sycdn.imooc.com/533e4c0500010c7602000200-100-100.jpg)
TA贡献1825条经验 获得超4个赞
看看这个,你必须进行全局匹配,你的正则表达式正在寻找返回的第一个匹配。您必须/gi在正则表达式中匹配多个。
var convertTextToHTML = $("#systemNotificationMsg").text();
var conversation = convertTextToHTML.replace(/((([A-Za-z]{3,9}:(?:\/\/)?)(?:[-;:&=\+\$,\w]+@)?[A-Za-z0-9.-]+|(?:www.|[-;:&=\+\$,\w]+@)[A-Za-z0-9.-]+)((?:\/[\+~%\/.\w-_]*)?\??(?:[-\+=&;%@.\w_]*)#?(?:[\w]*))?)/gi, function(text, link) {
console.log("Link in text: "+ link);
return '<a href="http://'+ link +'"> ' + link + ' </a>';
});
$("#systemNotificationMsg").html(conversation);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="systemNotificationMsg">
This message contains a link to www.google.com/hungerbox
and another to www.google.com so this is the example
</div>
![?](http://img1.sycdn.imooc.com/54584de700017cbd02200220-100-100.jpg)
TA贡献1893条经验 获得超10个赞
这可以通过稍微简单的正则表达式来实现。
我在这里更新了 JSFiddle:
https://jsfiddle.net/Lxnfq95b/1/
正则表达式现在是:
/(www|https?)([^\s]+)/g
请注意,/g
需要使其替换所有。
(www|https?)
将匹配 www. 或 http(s) 链接。
([^\s]+)
将使正则表达式继续,直到遇到空格字符。
添加回答
举报