通常咱们常常看到一些在帖子或者别人的文章里,文字中间还会夹带着不少的网址还有URL并且URL仍是能够点击进去的;还有另一个较经常使用到的地方就是聊天系统中识别对话的URL,废话很少说,入正题请看下面的代码!javascript
// 从字符串中提取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://www.cnblogs.com/jacko这是个人博客网站');
alert(result);
(上面的正则是匹配URL没有www开头,若是有须要能够加个判断)java
<script type="text/javascript"> str = 'http://www.cnblogs.com/jacko'; result = str.match(/((?:http:\/\/)?w{3}(?:.[\w]+)+)/g); if (result == null) { result = str.match(/((?:http:\/\/)?(?:.[\w]+)+)/g); }; document.write(result); </script>