一、`indexOf()`方法
在JS中,我們可以使用`indexOf()`方法來判斷一個字符串中是否包含另一個字符串,該方法會返回目標字符串在源字符串中第一次出現的位置。如果沒有匹配到目標字符串,則返回-1。
const str = "hello world"; console.log(str.indexOf("world")); // 6 console.log(str.indexOf("hello")); // 0 console.log(str.indexOf("test")); // -1
當目標字符串在源字符串中出現多次時,該方法只返回第一次出現的位置。
const str = "hello world, world"; console.log(str.indexOf("world")); // 6 console.log(str.lastIndexOf("world")); // 12
二、`includes()`方法
`includes()`方法也可以用來判斷一個字符串是否包含另一個字符串,該方法會返回一個布爾值,如果源字符串包含目標字符串,則返回true,否則返回false。
const str = "hello world"; console.log(str.includes("world")); // true console.log(str.includes("hello")); // true console.log(str.includes("test")); // false
三、`search()`方法
`search()`方法也可以用來判斷一個字符串是否包含另一個字符串,該方法會返回一個目標字符串在源字符串中第一次出現的位置。如果沒有匹配到目標字符串,則返回-1。
const str = "hello world"; console.log(str.search("world")); // 6 console.log(str.search("hello")); // 0 console.log(str.search("test")); // -1
四、正則表達式
使用正則表達式也可以判斷一個字符串中是否包含另一個字符串。
const str1 = "hello world"; const str2 = "world hello"; const regex = /world/; console.log(regex.test(str1)); // true console.log(regex.test(str2)); // true
五、`match()`方法
`match()`方法也可以用於判斷一個字符串中是否包含另一個字符串。該方法返回一個數組,其中包含了所有匹配到的字符串。
const str = "hello world, world"; console.log(str.match(/world/g)); // ["world", "world"] console.log(str.match(/test/g)); // null
總結
我們可以使用多種方式判斷一個字符串中是否包含另一個字符串,其中`indexOf()`方法、`includes()`方法和`search()`方法是基於字符串的操作,而正則表達式和`match()`方法則更加強大,可以匹配更多的情況。
原創文章,作者:KACID,如若轉載,請註明出處:https://www.506064.com/zh-hk/n/366335.html