一、使用includes()函數
1、includes()函數是ES6中新增的字元串方法,用於判斷一個字元串是否包含另一個字元串。該方法返回一個布爾值,如果包含則為true,不包含則為false。
2、includes()函數的語法如下:
str.includes(searchString[, position])
其中,searchString是要查找的字元串,必需。position是可選的,表示從字元串的哪個索引開始查找,默認值為0。
3、下面是一個示例代碼:
const str = 'hello world'
console.log(str.includes('world')) // 輸出 true
二、使用indexOf()函數
1、indexOf()函數同樣是用於查找字元串中某個子字元串的位置,如果包含則返回該子串首次出現的位置,否則返回-1。
2、indexOf()函數的語法如下:
str.indexOf(searchValue[, fromIndex])
其中,searchValue是要查找的字元串,必需。fromIndex是可選的,表示從字元串的哪個索引開始查找。
3、下面是一個示例代碼:
const str = 'hello world'
console.log(str.indexOf('world')) // 輸出 6
三、使用正則表達式
1、在JS中也可以使用正則表達式來判斷一個字元串是否包含某個字元。可以使用test()函數來測試一個字元串是否匹配某個模式,如果匹配則返回true,否則返回false。
2、下面是一個示例代碼:
const str = 'hello world'
const pattern = /world/
console.log(pattern.test(str)) // 輸出 true
四、使用字元串的match()方法
1、match()方法同樣是用於查找字元串中的子字元串。該方法支持傳入一個字元串或正則表達式,並返回一個數組,其中包含所有匹配的子串。
2、match()函數的語法如下:
str.match(regexp)
其中,regexp可以是一個字元串或一個正則表達式。
3、下面是一個示例代碼:
const str = 'hello world'
const pattern = /world/
console.log(str.match(pattern)) // 輸出 ["world"]
五、使用ES6的模板字元串
1、ES6的模板字元串中支持使用${}來引用變數。如果在${}中引用的字元串中包含搜索的字元,則說明該字元串包含該字元。
2、下面是一個示例代碼:
const str = 'hello world'
const char = 'world'
if (str.includes(`${char}`)) {
console.log('包含該字元')
} else {
console.log('不包含該字元')
}
通過以上五個方法,我們可以在JS中方便地判斷一個字元串是否包含某個字元或子串。
原創文章,作者:PBTFI,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/370354.html