萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

jQuery 文本鏈接自動識別插件:URL、郵箱、@提及、#話題一鍵轉為可點擊鏈接

功能需求

將純文本中的:

  • 完整 URL(http/https/ftp)
  • 郵箱地址
  • Twitter 風格 @username 提及
  • Twitter 風格 #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);
  });
};

正則表達式深度解析

URL 正則拆解

/((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>

注意:原版插件未處理郵箱地址,實際項目中建議補充郵箱正則。

增強版:支持郵箱、自定義鏈接模板、XSS 防護

$.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' // 站內話題鏈接
});

安全與性能注意事項

  1. XSS 風險:直接 .html() 會執行文本中夾帶的腳本。必須先獲取純文本 .text() 再替換後 .html(),或使用 DOMPurify 淨化。
  2. 已有鏈接重複處理:若容器內已有 <a>,.html() 會導致雙重包裹。解決:遍歷 childNodes 僅處理 Node.TEXT_NODE(3)。
  3. 大文本性能:萬字級文本多次 replace 會卡主線程。可用 requestIdleCallback 分片處理或 Web Worker。
  4. 國際化域名/表情符號:\w 不匹配 Unicode 字符,需用 [\p{L}\p{N}_-] (ES2018+ 支持 u 旗標) 或專用庫 linkifyjs。

生產級推薦庫

  • linkifyjs:健壯、支持插件(mention、hashtag)、輸出 HTML/React/Element、Tree-shakable
  • autolinker:功能豐富、可配置性高、TypeScript 原生
  • Twitter-text:Twitter 官方解析庫,精準匹配其規範

總結

tweetify 展示了「正則替換 + 模板字符串」實現自動鏈接化的經典模式。理解正則捕獲組、替換函數、XSS 防護、文本節點遍歷等細節,能構建生產可用的富文本解析組件。現代項目建議直接集成 linkifyjs 等成熟庫,專注業務邏輯而非造輪子。

copyright © 萬盛學電腦網 all rights reserved