indexOf(小程序不支持,不支持,不支持)
檢索是否包含某字符串,返回值是首次找到的當前字符的下標,沒找到返回-1
var str = "hello world"; console.log(str.indexOf("hello")); ====>0 console.log(str.indexOf("World")); ====>-1 console.log(str.indexOf("world")); ====>6
search
跟indexof很像,但是search可以用正則檢索
var str="hello World"; console.log(str.search(/World/)); ====>6 console.log(str.search(/world/)); ====>-1 console.log(str.search(/world/i); ====>6
match
方法能夠找出所有匹配的子字符串,並以數組的形式返回。
如果沒有找到匹配字符,則返回 null,而不是空數組。
var s = "http://c.biancheng.net"; var a = s.match(/c/n); //全局匹配所有字符c console.log(a); //返回數組[c,c]。
str.includes('')
有返回true,沒有返回false。也不用為記住-1而發愁了
let str = 'Hello World!'; console.log(str.includes('H'));//true console.log(str.includes('a'));//false
startsWith()
判斷該字符串是否為某個字符串的首位。有就是true,不是就是false。
endsWith()和startsWith()相反。判斷是否為末尾。
let str = 'Hello World!'; console.log(str.startsWith('H'));//true console.log(str.startsWith('Hello'));//true console.log(str.startsWith('e'));//false
let str = 'Hello World!'; console.log(str.endsWith('!'));//true console.log(str.endsWith('d!'));//true console.log(str.endsWith('e'));//false
這三個方法都支持第二個參數,表示看是搜索的位置。
let str = 'Hello World!'; console.log(str.includes('World',5));//true 從索引5(包含索引5)開始搜索 console.log(str.includes('World',7));//false console.log(str.startsWith('lo',3))//true console.log(str.startsWith('H',3));//false console.log(str.endsWith('el',3));//true endsWith()和上面兩個不一樣,它的第二個參數代表前幾個。“Hel”,所以返回true