摘要:一般我们经常看到一些在帖子或者别人的文章里,文字中间还会夹带着很多的网址还有URL而且URL还是可以点击进去的;还有另外一个较常用到的地方就是聊天系统中识别对话的URL,废话不多说,入正题请看下面的代码!// 从字符串中提取url function matchUrl(str){ &n
一般我们经常看到一些在帖子或者别人的文章里,文字中间还会夹带着很多的网址还有URL而且URL还是可以点击进去的;还有另外一个较常用到的地方就是聊天系统中识别对话的URL,废话不多说,入正题请看下面的代码!
// 从字符串中提取url
function matchUrl(str){
res = str.replace(/((?:http:\/\/)(?:.[\w]+)+)/g,function(){
if (/^http/.test(arguments[1]))
{
return "<a class='urlTag'" + " onclick=webPage('"+arguments[1]+"') " +"href='javascript:void(0)'>"+arguments[1]+"</a>";
} else {
return "<a class='urlTag'" + " onclick=webPage('http://"+arguments[1]+"') " +"href='javascript:void(0)'>"+arguments[1]+"</a>";
}
});
return res;
}
result = matchUrl('http://blog.csdn.net/jacko_chan这是我的博客网站');
alert(result);(上面的正则是匹配URL没有www开头,如果有需要可以加个判断)
<script type="text/javascript">
str = 'http://www.baidu.com';
result = str.match(/((?:http:\/\/)?w{3}(?:.[\w]+)+)/g);
if (result == null) {
result = str.match(/((?:http:\/\/)?(?:.[\w]+)+)/g);
};
document.write(result);
</script>