在 JavaScript 中使用 include() 檢查字符串是否包含子字符串
使用 String.includes()
檢查字符串是否包含子字符串 在 JavaScript 中:
- 調用
String.includes()
字符串上的方法。 - 將子字符串作為參數傳遞,例如
String.includes(substr)
. String.includes()
方法返回true
如果子字符串包含在字符串中。否則,false
被退回。
const str = 'React is a popular JavaScript library.'
const substr = 'React'
if (str.includes(substr)) {
console.log(`String contains "${substr}"`)
} else {
console.log(`String does not contain "${substr}"`)
}
// String contains "React"
String.includes()
方法有兩個參數:
searchString
— 要在此字符串中搜索的子字符串。position
— 開始搜索的索引。此參數是可選的。如果未指定,搜索將從零開始。
這是另一個使用 String.includes()
的示例 檢查句子中是否存在單詞:
const sentence = 'The JavaScript is a client-side language.'
const word = 'language'
console.log(`The word "${word}" is ${sentence.includes(word) ? 'present' : 'not present'}.`)
// The word is present.
String.includes()
方法區分大小寫,這意味著它對大寫和小寫字符的作用不同。以下表達式將返回 false
:
'JavaScript Jobs'.includes('jobs') // false
在上面的示例中,第二個參數被跳過,因為我們希望搜索從字符串的開頭開始。大多數時候,第二個參數是不需要的。
不過可以使用第二個參數來限制搜索範圍,如下圖:
const str = 'How are you doing? I am much better.'
str.includes('much', 20) // true
如果起始索引大於等於字符串的長度,String.includes()
方法不執行任何搜索,只返回 false
:
'My name is Atta!'.includes('Atta', 20) // false
如果起始索引小於 0,則 String.includes()
方法搜索整個字符串,就好像沒有指定索引一樣:
const str = 'Welcome to my blog!'
str.includes('blog', -5) // true
String.includes()
除 Internet Explorer 和一些舊版 Android 瀏覽器外,所有現代瀏覽器都支持該方法。但是,您可以輕鬆添加以下 polyfill 以在所有瀏覽器上使用它:
if (!String.prototype.includes) {
String.prototype.includes = function(search, start) {
'use strict';
if (typeof start !== 'number') {
start = 0;
}
if (start + search.length > this.length) {
return false;
} else {
return this.indexOf(search, start) !== -1;
}
};
}
注意第一行。它功能檢測對 String.includes()
的支持 並且僅在瀏覽器不支持 String.includes()
時才加載 polyfill 方法。
閱讀本文以了解可用於檢查字符串中是否存在子字符串的其他 JavaScript 函數。