萬盛學電腦網

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

JavaScript 字串處理實戰:從 DOM 取得連結文字並導向

實務上常需從 DOM 元素擷取文字內容並作為導向依據。本文示範標準 DOM API 取代舊式 `getElementById` 全域函式,並處理 HTML 實體、空白字元等細節。

問題情境

<a id="link" href="javascript:void(0)" onclick="goLink()">mailto:user@example.com</a>

需求:點擊時取得連結文字「mailto:user@example.com」並導向。

現代標準寫法

function goLink() {
  const linkEl = document.getElementById('link');
  if (!linkEl) return;
  
  // 1. 取得純文字內容(自動處理 HTML 實體、移除標籤)
  let text = linkEl.textContent.trim();
  
  // 2. 若包含前綴如 "mailto:",可直接導向
  if (text.startsWith('mailto:') || text.startsWith('tel:')) {
    window.location.href = text;
    return;
  }
  
  // 3. 一般 URL 補全協定
  if (!/^[a-z]+:/i.test(text)) {
    text = 'https://' + text;
  }
  window.location.href = text;
}

// 事件綁定分離(不寫在 HTML onclick)
document.addEventListener('DOMContentLoaded', () => {
  document.getElementById('link')?.addEventListener('click', goLink);
});

進階:解析任意連結格式

/**
 * 從元素文字內容解析可導向的 URL
 * @param {HTMLElement} el
 * @returns {string|null} 解析後的 URL 或 null
 */
function parseLinkFromElement(el) {
  if (!el) return null;
  let text = el.textContent.trim();
  if (!text) return null;
  
  // 移除常見包裹字元
  text = text.replace(/^[\[\(\{『《【]*/, '').replace(/[\]\)\}』》】]*$/, '');
  
  // 協定檢測
  const protocols = ['http:', 'https:', 'mailto:', 'tel:', 'ftp:', 'sms:'];
  if (protocols.some(p => text.toLowerCase().startsWith(p))) {
    return text;
  }
  
  // 類網址格式:含點號、無空白
  if (/^[^\s]+\.[^\s]+$/.test(text)) {
    return 'https://' + text;
  }
  
  return null; // 無法解析
}

常見字串處理 API 速查

需求方法範例
取得純文字el.textContent`el.textContent.trim()`
取得 HTMLel.innerHTML`el.innerHTML`
移除首尾空白.trim()`' abc '.trim()` → `'abc'`
移除所有空白.replace(/\s+/g, '')`'a b c'.replace(/\s+/g, '')` → `'abc'`
子字串位置.indexOf() / .lastIndexOf()`'abc'.indexOf('b')` → `1`
擷取子字串.substring(start, end) / .slice()`'abcde'.substring(1,3)` → `'bc'`
分割字串.split(separator)`'a,b,c'.split(',')` → `['a','b','c']`
取代(首次/全部).replace() / .replaceAll()`'a a'.replace('a','b')` → `'b a'`
正則比對.match(regex) / .matchAll()`'2024-01-01'.match(/\d{4}/g)` → `['2024']`

安全性提醒

  • **永不**直接 `eval()` 或 `new Function()` 執行取自 DOM 的字串。
  • 導向前驗證 URL 協定,避免 `javascript:` 協定注入。
  • 使用 `URL` 建構子驗證合法性:`new URL(text)` 若拋錯則不合法。

善用 `textContent`、`trim()`、`startsWith()` 等現代 API,能寫出更安全、更簡潔的字串處理邏輯。

copyright © 萬盛學電腦網 all rights reserved