萬盛學電腦網

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

JavaScript 字串包含判斷:`includes`、`indexOf`、正則與效能完整比較

現代標準:`String.prototype.includes` (ES2016)

const str = 'Hello World';
console.log(str.includes('World')); // true
console.log(str.includes('world')); // false(區分大小寫)
console.log(str.includes('World', 6)); // true(從索引 6 開始找)
  • 回傳 `boolean`,語意最清晰。
  • 支援第二參數 `position`(起始索引)。
  • IE **不支援**,需 Polyfill 或 Babel 轉譯。

傳統寫法:`indexOf` (ES5)

const str = 'Hello World';
console.log(str.indexOf('World') !== -1); // true
console.log(str.indexOf('world') !== -1); // false
console.log(str.indexOf('World', 6) !== -1); // true
  • 回傳索引(找到 ≥0,找不到 -1),需額外比較 `-1`。
  • 全瀏覽器支援(含 IE6+)。
  • 效能與 `includes` 幾乎相同(V8 內部同一套實作)。

正則表達式:`RegExp.prototype.test` / `String.prototype.search`

const str = 'Hello World';
console.log(/World/.test(str)); // true
console.log(/world/i.test(str)); // true(忽略大小寫)
console.log(str.search(/World/)); // 6(索引),找不到 -1
  • 需動態建構 `RegExp` 時注意特殊字符轉義:`new RegExp(escapeRegExp(keyword), 'i')`。
  • 效能較 `includes`/`indexOf` 稍慢(需編譯正則),但支援複雜模式。

效能基準測試(V8 / Chrome 120,百萬次迴圈)

const str = 'a'.repeat(1000) + 'target' + 'b'.repeat(1000);
const needle = 'target';

console.time('includes'); for(let i=0;i<1e6;i++) str.includes(needle); console.timeEnd('includes'); // ~45ms
console.time('indexOf');  for(let i=0;i<1e6;i++) str.indexOf(needle) !== -1; console.timeEnd('indexOf');  // ~42ms
console.time('regex');    for(let i=0;i<1e6;i++) /target/.test(str); console.timeEnd('regex');    // ~68ms
console.time('search');   for(let i=0;i<1e6;i++) str.search(/target/); console.timeEnd('search');   // ~70ms

結論:**`indexOf` ≈ `includes` > `test` > `search`**。實務差異微乎其微,優先考慮可讀性。

大小寫不敏感搜尋

// 方案 1:雙方 toLowerCase(簡單、效能佳)
str.toLowerCase().includes(needle.toLowerCase());

// 方案 2:正則 i 標誌
new RegExp(needle.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'), 'i').test(str);

// 方案 3:Intl.Collator (ES2021,語系感知)
new Intl.Collator(undefined, { sensitivity: 'base' }).compare(str, needle) === 0; // 僅完全相等
// 搜尋子字串需自行實作,較複雜

陣列版對應:`Array.prototype.includes` / `indexOf`

[1,2,3].includes(2); // true
[1,2,3].indexOf(2) !== -1; // true
// NaN 處理差異
[NaN].includes(NaN); // true ✅
[NaN].indexOf(NaN);  // -1 ❌ (NaN !== NaN)

Polyfill(支援 IE)

// String.includes
if (!String.prototype.includes) {
  String.prototype.includes = function(search, start) {
    return this.indexOf(search, start) !== -1;
  };
}
// Array.includes
if (!Array.prototype.includes) {
  Array.prototype.includes = function(search, fromIndex) {
    return this.indexOf(search, fromIndex) !== -1;
  };
}

最佳實踐建議

場景推薦方法理由
單純子字串存在性`str.includes(sub)`語意最清晰、ES2016 標準
需支援 IE 且不想 Polyfill`str.indexOf(sub) !== -1`零兼容成本
大小寫不敏感`str.toLowerCase().includes(sub.toLowerCase())`效能最佳、無正則編譯開銷
複雜模式(邊界、替換、捕獲組)`RegExp`功能最強
陣列含 NaN 判斷`arr.includes(NaN)`唯一能正確判斷 NaN

結語

字串包含判斷,**首選 `includes`**,兼容舊瀏覽器加 Polyfill 或用 `indexOf !== -1`。大小寫不敏感用 `toLowerCase()` 而非正則,效能更好。陣列同理,且 `includes` 能正確處理 `NaN`。別再寫 `~str.indexOf(sub)` 這類位元運算技巧了——可讀性差且無效能優勢。

copyright © 萬盛學電腦網 all rights reserved