endsWith()
1. 前言
上一節(jié) 我們學(xué)到了字符串的方法 startsWith()
用于判斷是否以一個(gè)指定字符串為起始。 本節(jié)介紹 ES6 中新增的與之相反的字符串方法 endsWith()
,該方法用來判斷當(dāng)前字符串是否是以另外一個(gè)給定的子字符串為結(jié)尾。
2. 方法詳情
endsWith()
用于判斷當(dāng)前字符串,是否以一個(gè)指定字符串為結(jié)尾的,如果在字符串的結(jié)尾找到了給定的字符則返回 true,否則返回 false。
使用語法:
str.endsWith(searchString[, length])
參數(shù)說明:
參數(shù) | 描述 |
---|---|
searchString | 需要查詢的子字符串 |
length | (可選) 作為 str 的長度。默認(rèn)值為 str.length |
實(shí)例:
const str1 = 'Cats are the best!';
console.log(str1.endsWith('best', 17)); // true
const str2 = 'Is this a question';
console.log(str2.endsWith('?')); // false
3. 使用場(chǎng)景
查詢一個(gè)字符串是否在另一個(gè)字符串的末尾。
3.1 沒有參數(shù)
這里需要說明一下的是,當(dāng)字符串調(diào)用 endsWith()
方法時(shí)不傳參數(shù)時(shí),默認(rèn)是 undefined
返回的結(jié)果是 false。
var str = "I love imooc.";
console.log(str.endsWith()); // false
console.log(str.endsWith(undefined)); // false
上面的代碼中,第 2 行和第 3 行是等價(jià)的,因?yàn)榈谝粋€(gè)參數(shù)是必填的,所以在當(dāng)我們沒有傳參時(shí),默認(rèn)使用 undefined
來填充,注意這里不是字符串類型的 ‘undefined’
3.2 一個(gè)參數(shù)
var str = "I love imooc.";
console.log(str.endsWith("I love")); // false
console.log(str.endsWith("imooc")); // false
console.log(str.endsWith("imooc.")); // true
console.log(str.endsWith("")); // true
從例子中我們可以看出,只有結(jié)尾有最后一個(gè)字符的時(shí)候,才會(huì)返回 true,只要沒有包含結(jié)尾的字符,即使查找的字符串在目標(biāo)字符串里也是返回 fasle 的。在查找空字符串時(shí),返回的結(jié)果是 true,那是因?yàn)榭兆址谌魏巫址卸际谴嬖诘摹?/p>
3.3 兩個(gè)參數(shù)
當(dāng)有第二個(gè)參數(shù)的時(shí)候,第二個(gè)參數(shù)是字符串的長度
var str = "I love imooc.";
console.log(str.endsWith("love", 6)); // true
console.log(str.endsWith("e", 6)); // true
從這兩個(gè) log 打印出來的結(jié)果可以看出,第二個(gè)參數(shù)會(huì)取原字符串的指定長度作為查找的目標(biāo)字符串,這里的第二個(gè)參數(shù)是 6 也就是取原字符串的 I love
,所以 endsWith
判斷是以 love
結(jié)尾的。
4. 小結(jié)
在查詢字符串中的結(jié)尾時(shí)最好使用 endsWith
進(jìn)行查詢,它的效率要比 includes()
高,而且 endsWith
也具有語義化。