'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。
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 支援 |
|---|---|---|---|---|
includes | str.includes(sub[, pos]) | boolean | ES2016 | ❌ |
indexOf | str.indexOf(sub[, pos]) | number (索引/-1) | ES1 | ✅ |
search | str.search(regexp) | number | ES1 | ✅ |
match | str.match(regexp) | Array/null | ES1 | ✅ |
test | regexp.test(str) | boolean | ES1 | ✅ |
includesif (url.includes('admin')) { /* 管理頁面 */ }
indexOfvar pos = str.indexOf('@');
if (pos > 0) { var user = str.slice(0, pos); }
testvar hasNumber = /\d/.test(str);
var isEmail = /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(str);
var keywords = ['error', 'fail', 'exception'];
var hasError = keywords.some(k => log.includes(k));
<!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 自動降級。const includes = (str, sub) => str.includes(sub);。