萬盛學電腦網

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

JavaScript 字符串包含判斷:contains、includes、indexOf 多種方案與 Polyfill

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

'hello world'.includes('world'); // true
'hello world'.includes('World'); // false(區分大小寫)
'hello world'.includes('world', 6); // false(從索引 6 開始找)

瀏覽器支援:Chrome 41+、Firefox 40+、Edge 12+、Safari 9+。IE 全系不支援,需 Polyfill。

Polyfill 實現(兼容 IE)

if (!String.prototype.includes) {
  String.prototype.includes = function(search, start) {
    'use strict';
    if (typeof search === 'undefined') search = '';
    var str = String(this);
    var pos = Math.min(Math.max(start | 0, 0), str.length);
    return str.indexOf(search, pos) !== -1;
  };
}

註:原文使用 !!~this.indexOf(arg) 技巧(~ 位運算將 -1 變 0,其餘非 0),雖簡潔但可讀性較差,現代代碼建議显式 !== -1。

替代方案對比

方法語法返回值ES 版本IE 支援
includesstr.includes(sub[, pos])booleanES2016❌
indexOfstr.indexOf(sub[, pos])number (索引/-1)ES1✅
searchstr.search(regexp)numberES1✅
matchstr.match(regexp)Array/nullES1✅
testregexp.test(str)booleanES1✅

實戰場景與最佳實踐

1. 簡單包含判斷 → includes

if (url.includes('admin')) { /* 管理頁面 */ }

2. 需要索引位置 → indexOf

var pos = str.indexOf('@');
if (pos > 0) { var user = str.slice(0, pos); }

3. 正則匹配(大小寫不敏感、邊界等) → test

var hasNumber = /\d/.test(str);
var isEmail = /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(str);

4. 多關鍵詞任一匹配

var keywords = ['error', 'fail', 'exception'];
var hasError = keywords.some(k => log.includes(k));

完整可運行示例(含 Polyfill 驗證)

<!DOCTYPE html>
<html><head><meta charset="utf-8"></head><body>
<input id="s1" placeholder="主字符串" value="a quick brown fox jumps over" style="width:300px">
<input id="s2" placeholder="子字符串" value="fox jumps" style="width:300px">
<button onclick="check()">檢測包含</button>
<pre id="result"></pre>

<script>
// Polyfill
if (!String.prototype.includes) {
  String.prototype.includes = function(search, start) {
    return String(this).indexOf(search, start) !== -1;
  };
}

function check() {
  var s1 = document.getElementById('s1').value;
  var s2 = document.getElementById('s2').value;
  document.getElementById('result').textContent = 
    'includes: ' + s1.includes(s2) + '\n' +
    'indexOf: ' + (s1.indexOf(s2) !== -1) + '\n' +
    'RegExp test: ' + new RegExp(s2.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')).test(s1);
}
</script>
</body></html>

總結

  • 現代項目:直接用 includes,配合 Babel/TypeScript 自動降級。
  • 無構建工具舊項目:複製上方 Polyfill(約 10 行)即可安全使用。
  • 避免擴展原型污染全局:模塊化項目中優先用獨立函數 const includes = (str, sub) => str.includes(sub);。
copyright © 萬盛學電腦網 all rights reserved