JavaScript字串搜索方法比較:indexOf vs includes vs filter

在JavaScript中,我們經常需要檢查一個字串是否包含某個特定的字元或子字串。本文將深入比較三種常用的方法:indexOf()includes(), 和filter()。我們將探討它們的語法、用法、優缺點,以及性能考慮。

1. indexOf() 方法

indexOf()是最古老和最廣泛支持的方法之一。

語法

1
string.indexOf(searchValue[, fromIndex])

用法

1
2
3
const str = "Hello, World!";
const hasO = str.indexOf('o') !== -1; // true
const hasZ = str.indexOf('z') !== -1; // false

優點

  • 兼容性好,支持舊版瀏覽器
  • 可以指定開始搜索的位置

缺點

  • 返回值不是布爾型,需要與-1比較
  • 代碼可讀性較差

2. includes() 方法

includes()是ES6引入的新方法,專門用於檢查字串是否包含特定子字串。

語法

1
string.includes(searchString[, position])

用法

1
2
3
const str = "Hello, World!";
const hasO = str.includes('o'); // true
const hasZ = str.includes('z'); // false

優點

  • 直接返回布爾值,更直觀
  • 代碼更簡潔,可讀性強
  • 可以指定開始搜索的位置

缺點

  • 不支持正則表達式
  • 在舊版瀏覽器中可能需要polyfill

3. filter() 方法

filter()主要用於數組,但也可以用於字串搜索。

語法

1
Array.from(string).filter(char => char === searchChar).length > 0

用法

1
2
3
const str = "Hello, World!";
const hasO = Array.from(str).filter(char => char === 'o').length > 0; // true
const hasZ = Array.from(str).filter(char => char === 'z').length > 0; // false

優點

  • 靈活性高,可以進行複雜的條件篩選
  • 可以同時查找多個字元

缺點

  • 語法較為複雜
  • 性能較差,特別是對於長字串

性能比較

為了比較這三種方法的性能,我們可以進行一個簡單的基準測試:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
const str = "Hello, World!".repeat(1000000); // 創建一個長字串
const searchChar = '!';

console.time('indexOf');
for (let i = 0; i < 100; i++) {
str.indexOf(searchChar) !== -1;
}
console.timeEnd('indexOf');

console.time('includes');
for (let i = 0; i < 100; i++) {
str.includes(searchChar);
}
console.timeEnd('includes');

console.time('filter');
for (let i = 0; i < 100; i++) {
Array.from(str).filter(char => char === searchChar).length > 0;
}
console.timeEnd('filter');

在我的測試中,得到了以下結果(結果可能因設備而異):

  • indexOf: 約 5ms
  • includes: 約 7ms
  • filter: 約 15000ms

結論

  1. 最佳性能: indexOf()略優於includes(),但差異通常可以忽略不計。
  2. 最佳可讀性: includes()提供了最清晰和直觀的語法。
  3. 最大靈活性: filter()允許更複雜的搜索邏輯,但性能較差。

建議

  • 對於簡單的字元或子字串搜索,優先使用includes()。它提供了良好的平衡:易讀性好,性能也不錯。
  • 如果需要支持舊版瀏覽器或需要知道字元的位置,使用indexOf()
  • 只在需要複雜搜索邏輯時使用filter()

記住,在大多數實際應用中,這些方法之間的性能差異是微不足道的。選擇最適合你的用例和代碼風格的方法才是最重要的。

參考資源