實務上常需從 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; // 無法解析
}
| 需求 | 方法 | 範例 |
|---|---|---|
| 取得純文字 | el.textContent | `el.textContent.trim()` |
| 取得 HTML | el.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']` |
善用 `textContent`、`trim()`、`startsWith()` 等現代 API,能寫出更安全、更簡潔的字串處理邏輯。