js从富文本中找出固定电话、手机号码、邮箱并添加上链接 (封装)
function richtextfindtel(value) {
/*固定电话、手机号码、邮箱*/
var tempValue = value.replace(/<[^>]+>/g, "");
var arrMatch = tempValue.match(/[0-9a-z][0-9a-z\-\_\.]+@([0-9a-z][0-9a-z\-]*\.)+[a-z]{2,}|0[0-9]{2,3}-{0,1}[2-9][0-9]{6,7}|[0-9]+/g);
//按长度排序,避免被提前替换
for (var i = 0; i < arrMatch.length; i++) {
for (var j = i + 1; j < arrMatch.length; j++) {
if (arrMatch[i].length < arrMatch[j].length) {
var tmp = arrMatch[i];
arrMatch[i] = arrMatch[j];
arrMatch[j] = tmp;
}
}
}
for (var match in arrMatch) {
var t = arrMatch[match];
var replacev = '';
//邮箱
if (/^[0-9a-z][0-9a-z\-\_\.]+@([0-9a-z][0-9a-z\-]*\.)+[a-z]{2,}$/.test(t)) {
replacev = '<a href=mailto:' + t + '">' + t + '</a>';
}
//固定电话
if (/^0[0-9]{2,3}-{0,1}[2-9][0-9]{6,7}$/.test(t)) {
replacev = '<a href=tel:' + t + '">' + t + '</a>';
}
//手机号码
else if (/^1([3|4|5|6|7|8|9])\d{9}$/.test(t) || /^\d{7,8}$/.test(t)) {
replacev = '<a href=tel:' + t + '">' + t + '</a>';
}
else {
replacev = t;
}
var reg = new RegExp("(?!<a .*?>.*?)" + t + "(?![^<]*<\/a>)", "gmi");
value = value.replace(reg, replacev);
}
return value;
}
网友评论