某客服系统匹配更多的超链接场景修改js实例 正则匹配url网址
只截取部分代码
分为手机端、电脑端、电脑后台端三个地方的修改
1、/public/assets/js/index/inchat.js
2、/public/assets/js/moblie/mochat.js
3、/public/assets/js/admin/chat.js
4、/public/assets/js/admin/mchat.js
优化前
优化后
//发送消息
var send = function () {
//获取 游客id
var msg = $("#text_in").val();
var reg = new RegExp( '<' , "g" )
var msg2 =msg.replace(reg,'<');
var reg2 = new RegExp( '>' , "g" )
msg2 =msg2.replace(reg2,'>');
/*
msg2 =msg2.replace('http://','');
msg2 =msg2.replace('https://','');
msg2=msg2.replace(/[a-z]+[.]{1}[a-z\d\-]+[.]{1}[a-z\d]*[\/]*[A-Za-z\d]*[\/]*[A-Za-z\d]*[\/]*[A-Za-z\d]*[\/]*[A-Za-z\d]/g,function (i) {
return 'http://'+i;
});
msg2=msg2.replace(/(https?|http|ftp|file):\/\/[-A-Za-z0-9+&@#/%?=~_|!:,.;]+[-A-Za-z0-9+&@#/%=~_|]/g,function (i) {
a=i.replace('http://','');
return '<a href="'+i+'" target="_blank">'+a+'</a>';
});
*/
msg2 = msg2.replace(/http:\/\//g, 'http:\/\/');
msg2 = msg2.replace(/https:\/\//g, 'https:\/\/');
//20240710
msg2 = msg2.replace(/[-A-Za-z0-9+&@#/%?=~_|!:,.;]*\.[A-Za-z]{2,}\/?[-A-Za-z0-9+&@#/%=~_|]*/g, function (match) {
if (match.includes('http://') || match.includes('https://')) {
return '<a href="' + match + '" target="_blank">' + match + '</a>';
} else {
return '<a href="http://' + match + '" target="_blank">' + match + '</a>';
}
});
主要起作用的代码:
//20240710修改的,加强了链接识别,加强了后缀识别
msg = msg.replace(/http:\/\//g, 'http:\/\/');
msg = msg.replace(/https:\/\//g, 'https:\/\/');
//20240710
msg = msg.replace(/[-A-Za-z0-9+&@#/%?=~_|!:,.;]*\.[A-Za-z]{2,}\/?[-A-Za-z0-9+&@#/%=~_|]*/g, function (match) {
if (match.includes('http://') || match.includes('https://')) {
return '<a href="' + match + '" target="_blank">' + match + '</a>';
} else {
return '<a href="http://' + match + '" target="_blank">' + match + '</a>';
}
});