JS验证文本中是否有链接

http://www.soulteary.com/2014/12/05/better-url-regexp-in-js.html

参考以上地址写的替换文本中URL的方法

 

function replaceSrc(txt){
var reg = /(((https?:(?:\/\/)?)(?:[-;:&=\+\$,\w]+@)?[A-Za-z0-9.-]+|(?:www.|[-;:&=\+\$,\w]+@)[A-Za-z0-9.-]+)((?:\/[\+~%\/.\w-_]*)?\??(?:[-\+=&;%@.\w_]*)#?(?:[\w]*))?)/ig;
var result = txt.replace(reg,function(item){
return "<a href='"+item+"' target='_blank'>"+item+"</a>";
});
return result;
}

 

EG:

var str = '1231www.baidu.com hahaha http://hao123.com 123123';

replaceSrc(str);

 

 

结果返回:1231 <a href="www.baidu.com" target="_blank">www.baidu.com</a> hahaha <a href="http://hao123.com" target="_blank">http://hao123.com</a> 123123

posted @ 2016-11-08 13:28  有间小屋在森林  阅读(2236)  评论(0编辑  收藏  举报