通常咱們常常看到一些在帖子或者別人的文章裏,文字中間還會夾帶着不少的網址還有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>