在留言板、聊天室、富文本編輯器等場景中,將使用者輸入的純文字網址自動識別並轉換為 <a> 標籤,能大幅提升使用者體驗。核心步驟為:正則匹配 URL → 替換為帶 href 的錨點標籤。
支援 http、https、ftp、ftps 協定、IP 位址、連結埠、查詢參數等常見格式:
const urlRegex = /(https?:\/\/|ftps?:\/\/)?((\d{1,3}\.){3}\d{1,3}(:\d+)?|([\w]+\.)+\w{2,4}(:\d+)?)(?\/[\w#!:.?+=&%@!\-\/]*)?/ig;
function replaceURLToLink(text) {
return text.replace(urlRegex, function(url) {
let href = url;
if (!/^https?:\/\//i.test(url)) {
href = 'https://' + url; // 補全協定
}
return '<a href="' + href + '" target="_blank" rel="noopener noreferrer">' + url + '</a>';
});
}
const raw = '請訪問 https://example.com 或 example.org 查看詳情。';
const html = replaceURLToLink(raw);
// 結果:請訪問 <a href="https://example.com" target="_blank">https://example.com</a> 或 <a href="https://example.org" target="_blank">example.org</a> 查看詳情。
document.createTreeWalker 逐節點處理,避免破壞既有標籤結構。此功能為前端文字豐富化處理的經典案例,掌握正則與 replace 回調函式是關鍵。