endsWith()
1. 前言
上一節 我們學到了字符串的方法 startsWith()
用于判斷是否以一個指定字符串為起始。 本節介紹 ES6 中新增的與之相反的字符串方法 endsWith()
,該方法用來判斷當前字符串是否是以另外一個給定的子字符串為結尾。
2. 方法詳情
endsWith()
用于判斷當前字符串,是否以一個指定字符串為結尾的,如果在字符串的結尾找到了給定的字符則返回 true,否則返回 false。
使用語法:
str.endsWith(searchString[, length])
參數說明:
參數 | 描述 |
---|---|
searchString | 需要查詢的子字符串 |
length | (可選) 作為 str 的長度。默認值為 str.length |
實例:
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. 使用場景
查詢一個字符串是否在另一個字符串的末尾。
3.1 沒有參數
這里需要說明一下的是,當字符串調用 endsWith()
方法時不傳參數時,默認是 undefined
返回的結果是 false。
var str = "I love imooc.";
console.log(str.endsWith()); // false
console.log(str.endsWith(undefined)); // false
上面的代碼中,第 2 行和第 3 行是等價的,因為第一個參數是必填的,所以在當我們沒有傳參時,默認使用 undefined
來填充,注意這里不是字符串類型的 ‘undefined’
3.2 一個參數
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
從例子中我們可以看出,只有結尾有最后一個字符的時候,才會返回 true,只要沒有包含結尾的字符,即使查找的字符串在目標字符串里也是返回 fasle 的。在查找空字符串時,返回的結果是 true,那是因為空字符在任何字符串中都是存在的。
3.3 兩個參數
當有第二個參數的時候,第二個參數是字符串的長度
var str = "I love imooc.";
console.log(str.endsWith("love", 6)); // true
console.log(str.endsWith("e", 6)); // true
從這兩個 log 打印出來的結果可以看出,第二個參數會取原字符串的指定長度作為查找的目標字符串,這里的第二個參數是 6 也就是取原字符串的 I love
,所以 endsWith
判斷是以 love
結尾的。
4. 小結
在查詢字符串中的結尾時最好使用 endsWith
進行查詢,它的效率要比 includes()
高,而且 endsWith
也具有語義化。