DIV CSS 佈局教程網

用正則表達式從文字中辨識並轉換 URL
編輯:JavaScript基礎知識     

我們常會看到,在論壇文章或他人分享的文字裡,段落之間夾雜著不少網址與 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('https://"+arguments[1]+"') " +"href='javascript:void(0)'>"+arguments[1]+"</a>"; } }); return res; } 
result = matchUrl('https://hovertree.com/map這是一個開發網站'); 

alert(result);

(上面的正則匹配的是不含 www 開頭的 URL,若有需要,可以自行加上一個判斷分支。)

<script type="text/javascript"> str = 'https://www.baidu.com'; result = str.match(/((?:http:\/\/)?w{3}(?:.[\w]+)+)/g); if (result == null) { result = str.match(/((?:http:\/\/)?(?:.[\w]+)+)/g); }; document.write(result); </script> 
XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved