我正在尝试检测URL并在用户键入textarea时将其替换为超链接。我正在尝试使用正则表达式测试URL的字符串:
var text='gggg.com/gd/';
var exp = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig;
var text1=text.replace(exp, "<a href='$1'>$1</a>");
var exp2 =/(^|[^\/])(www\.[\S]+(\b|$))/gim;
var finalText=text1.replace(exp2, '$1<a target="_blank" href="http://$2">$2</a>');
alert(finalText);
对于参数为ot但没有http(s)但未能识别没有http和www的URL的URL,它可以正常工作。 abc.com或anc.com/fgdg/dgd或abc.com?lklkj=kjhkjh
更新
根据epascarello的评论和Ali Khan的答案:
var text='gggg.com?klk=efhjsk';
var exp2 = '^([a-zA-Z0-9]+(\.[a-zA-Z0-9]+)+.*)$';
var pattern1 = /^([a-zA-Z0-9]+(\.[a-zA-Z0-9]+)+.*)$/;
if(pattern1.test(text) && text.substr(0,3)!='www'){
var finalText = '<a href="'+text+'" target="_blank">'+text+'</a>';
}else{
var exp = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig;
var text1=text.replace(exp, "<a href='$1'>$1</a>");
var exp2 =/(^|[^\/])(www\.[\S]+(\b|$))/gim;
var finalText=text1.replace(exp2, '$1<a target="_blank" href="http://$2">$2</a>');
}
alert(finalText);
答案 0 :(得分:-1)
试试这个
^([a-zA-Z0-9]+(\.[a-zA-Z0-9]+)+.*)$