萬盛學電腦網

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

JavaScript indexOf() 深度解析:字串搜尋、效能與現代替代方案

基本語法與行為

str.indexOf(searchString[, fromIndex])

// 參數
// searchString: 要搜尋的子字串 (會被轉為字串)
// fromIndex: 可選,開始搜尋的索引 (預設 0),負數視為 0,超過長度視為 length

// 回傳值
// 找到:第一次出現的索引 (0-based)
// 未找到:-1

核心範例

const quote = "To be, or not to be.";

quote.indexOf("To be");     // 0 (開頭)
quote.indexOf("be");        // 3 (第一個 "be")
quote.indexOf("be", 4);     // 17 (從索引 4 開始找,找到第二個 "be")
quote.indexOf("not");       // 10
quote.indexOf("missing");   // -1 (不存在)
quote.indexOf("");          // 0 (空字串永遠在索引 0)
quote.indexOf("", 5);       // 5 (空字串在任何有效索引)

lastIndexOf():從末尾向前搜尋

const str = "abracadabra";

str.indexOf("a");        // 0
str.lastIndexOf("a");    // 10 (最後一個 'a')
str.indexOf("bra");      // 1
str.lastIndexOf("bra");  // 8

實戰應用場景

1. 瀏覽器偵測 (經典但不推薦)

// 老寫法
var ua = navigator.userAgent;
if (ua.indexOf("MSIE") !== -1 || ua.indexOf("Trident") !== -1) {
  // IE
}

// 現代寫法:特性偵測
const isIE = !!document.documentMode; // IE10-11
// 或使用 Modernizr、bowser 等庫

2. URL/路徑解析

const url = "https://example.com/path/to/page?query=value#hash";

const protocolEnd = url.indexOf("://"); // 5
const pathStart = url.indexOf("/", protocolEnd + 3); // 22
const queryStart = url.indexOf("?"); // 33
const hashStart = url.indexOf("#");  // 41

// 更好:new URL() API
const u = new URL(url);
console.log(u.protocol, u.pathname, u.search, u.hash);

3. 字串包含檢查 (現代用 includes())

const tags = "javascript,vue,react,node";

// 老寫法
if (tags.indexOf("vue") !== -1) { /* ... */ }

// 現代寫法 (ES2016)
if (tags.includes("vue")) { /* ... */ }

// 陣列也支援
const arr = ["js", "ts", "vue"];
arr.includes("vue"); // true

4. 計算子字串出現次數

function countOccurrences(str, substr) {
  if (!substr) return 0;
  let count = 0, pos = 0;
  while ((pos = str.indexOf(substr, pos)) !== -1) {
    count++;
    pos += substr.length; // 避免重疊計數 (如 "aaa".indexOf("aa") → 0, 1)
  }
  return count;
}

console.log(countOccurrences("abababa", "aba")); // 2 (索引 0, 4)
console.log(countOccurrences("aaaa", "aa"));     // 2 (索引 0, 2) - 非重疊

5. 截取關鍵字前後文本

function extractContext(text, keyword, radius = 20) {
  const idx = text.indexOf(keyword);
  if (idx === -1) return null;
  const start = Math.max(0, idx - radius);
  const end = Math.min(text.length, idx + keyword.length + radius);
  return {
    before: text.slice(start, idx),
    match: text.slice(idx, idx + keyword.length),
    after: text.slice(idx + keyword.length, end)
  };
}

console.log(extractContext("The quick brown fox jumps", "fox", 10));
// { before: "brown ", match: "fox", after: " jumps" }

效能分析

方法時間複雜度備註
indexOfO(n × m)n=字串長度, m=搜尋串長度。瀏覽器內部優化 (Boyer-Moore 等)
lastIndexOfO(n × m)從末尾向前
includesO(n × m)語意更清晰、不需比較 -1
search(regexp)O(n × m)支援正則,但建立 RegExp 有開銷
matchAllO(n × m)獲取所有匹配含捕獲組

Unicode 與 Emoji 陷阱

⚠️ 代理對 (Surrogate Pairs) 問題

const emoji = "👨‍👩‍👧‍👦"; // 家庭 emoji: 4 個代碼點 + 3 個 ZWJ = 11 個 UTF-16 代碼單元
console.log(emoji.length); // 11 (UTF-16 代碼單元數)
console.log(emoji.indexOf("👩")); // 5 (在 UTF-16 層面找到)
// 但實際視覺上是單一字符!

// 正確處理:使用字符迭代器
[...emoji].indexOf("👩"); // 1 (正確的字符索引)
// 或
Array.from(emoji).indexOf("👩"); // 1

現代替代方案對比

需求推薦方法優點
單純存在性檢查str.includes(substr)語意明確、回傳布林、ES2016 標準
需要知道位置str.indexOf(substr)回傳索引、相容性最好
從末尾找位置str.lastIndexOf(substr)唯一原生反向搜尋
複雜模式匹配str.match(regexp) / matchAll正則表達式威力
Unicode 感知索引[...str].indexOf(char) 或 Intl.Segmenter正確處理 Emoji、組合字符
高效能大量搜尋Fuse.js (模糊搜尋)、search-index索引化、近似匹配

TypeScript 類型安全

// indexOf 回傳 number,需處理 -1
function findIndexSafe(str: string, search: string): number | null {
  const idx = str.indexOf(search);
  return idx === -1 ? null : idx;
}

// 使用
const idx = findIndexSafe("hello", "x");
if (idx !== null) { /* 找到 */ }

總結

indexOf() 是字串搜尋的基石方法,雖然有 includes()、match() 等現代替代品,但在需要索引位置、相容舊環境、簡單子字串定位場景下仍是首選。關鍵注意點:回傳 -1 而非 false、區分大小寫、UTF-16 代碼單元索引而非字符索引。處理國際化文本時,請使用 Intl.Segmenter 或展開運算子 [...str] 獲取真實字符索引。

copyright © 萬盛學電腦網 all rights reserved