將純文本中的:
@username 提及#hashtag 話題自動轉換為對應的 <a> 鏈接,支持自定義目標鏈接模板。
$.fn.tweetify = function() {
return this.each(function() {
var $this = $(this);
var html = $this.html();
// 1. URL 識別(支持 http/https/ftp、可選用戶信息、端口、路徑、查詢、錨點)
html = html.replace(
/((ftp|https?):\/\/(\w+:\w*@)?([\w.-]+)(:\d+)?(\/[\w#!:.?+=&%@!\-/]*)?)/gi,
'$1'
);
// 2. #話題 -> Twitter 搜索
html = html.replace(
/(^|\s)#(\w+)/g,
'$1#$2'
);
// 3. @提及 -> Twitter 個人主頁
html = html.replace(
/(^|\s)@(\w+)/g,
'$1@$2'
);
$this.html(html);
});
};
/((ftp|https?):\/\/(\w+:\w*@)?([\w.-]+)(:\d+)?(\/[\w#!:.?+=&%@!\-/]*)?)/gi
// 分組1: 整個URL
// 分組2: 協議 ftp|http|https
// 分組3: 用戶信息 user:pass@ (可選)
// 分組4: 域名/IP (包含子域、連字符、點)
// 分組5: 端口 :80 (可選)
// 分組6: 路徑/查詢/錨點 (可選)
// gi: 全局 + 忽略大小寫
(^|\s):行首或空白字符後(避免匹配 email@domain.com 中的 @)@(\w+) / #(\w+):捕獲用戶名/話題標籤(字母數字下劃線)$1,插入鏈接<div class="tweet-content">
關注 @official_account 了解最新資訊!查看 #前端開發 #JavaScript 話題。
官網:https://example.com/path?query=1#anchor
聯系:support@example.com
</div>
<script>
$('.tweet-content').tweetify();
</script>
<div class="tweet-content">
關注 <a href="https://twitter.com/official_account" target="_blank">@official_account</a> 了解最新資訊!
查看 <a href="https://twitter.com/search?q=%23%E5%89%8D%E7%AB%AF%E9%96%8B%E7%99%BC" target="_blank">#前端開發</a>
<a href="https://twitter.com/search?q=%23JavaScript" target="_blank">#JavaScript</a> 話題。
官網:<a href="https://example.com/path?query=1#anchor" target="_blank">https://example.com/path?query=1#anchor</a>
聯系:support@example.com
</div>
注意:原版插件未處理郵箱地址,實際項目中建議補充郵箱正則。
$.fn.autoLink = function(options) {
var opts = $.extend({
urlTemplate: '$1',
emailTemplate: '$1',
mentionTemplate: '@$1',
hashtagTemplate: '#$1',
// 自定義正則(需包含捕獲組)
urlRegex: /((?:https?|ftp):\/\/[\w.-]+(?:\:\d+)?(?:\/[\w#!:.?+=&%@!\-/]*)?)/gi,
emailRegex: /([a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,})/g,
mentionRegex: /(^|\s)@(\w+)/g,
hashtagRegex: /(^|\s)#(\w+)/g
}, options);
return this.each(function() {
var $this = $(this);
// 關鍵:獲取純文本內容,避免重複處理已生成的 標籤
var text = $this.text();
// 若需保留原有 HTML 結構,需用 tree walker 遍歷文本節點,此處簡化演示
text = text.replace(opts.urlRegex, opts.urlTemplate);
text = text.replace(opts.emailRegex, opts.emailTemplate);
text = text.replace(opts.mentionRegex, function(m, prefix, name) {
return prefix + opts.mentionTemplate.replace('$1', name);
});
text = text.replace(opts.hashtagRegex, function(m, prefix, tag) {
return prefix + opts.hashtagTemplate.replace('$1', tag);
});
$this.html(text);
});
};
// 使用
$('.comment-body').autoLink({
mentionTemplate: '@$1', // 站內用戶鏈接
hashtagTemplate: '#$1' // 站內話題鏈接
});
.html() 會執行文本中夾帶的腳本。必須先獲取純文本 .text() 再替換後 .html(),或使用 DOMPurify 淨化。<a>,.html() 會導致雙重包裹。解決:遍歷 childNodes 僅處理 Node.TEXT_NODE(3)。replace 會卡主線程。可用 requestIdleCallback 分片處理或 Web Worker。[\p{L}\p{N}_-] (ES2018+ 支持 u 旗標) 或專用庫 linkifyjs。tweetify 展示了「正則替換 + 模板字符串」實現自動鏈接化的經典模式。理解正則捕獲組、替換函數、XSS 防護、文本節點遍歷等細節,能構建生產可用的富文本解析組件。現代項目建議直接集成 linkifyjs 等成熟庫,專注業務邏輯而非造輪子。