includes 函數 語法
str.includes(searchString[, position])includes() 方法用於判斷一個字符串是否包含在另一個字符串中,根據情況返回 true 或 false。
includes() 方法是區分大小寫的,例如,下面的表達式會返回 false :
'Blue Whale'.includes('blue'); // returns false兼容補丁(polyfill)
if (!String.prototype.includes) {
String.prototype.includes = function(search, start) {
'use strict';
if (typeof start !== 'number') {
start = 0;
}
if (start + search.length > this.length) {
return false;
} else {
return this.indexOf(search, start) !== -1;
}
};
}示例
var str = 'To be, or not to be, that is the question.';
console.log(str.includes('To be')); // true
console.log(str.includes('question')); // true
console.log(str.includes('nonexistent')); // false
console.log(str.includes('To be', 1)); // false
console.log(str.includes('TO BE')); // falseindexOf 函數語法
str.indexOf(searchValue [, fromIndex])參數
searchValue
要被查找的字符串值。
如果沒有提供確切地提供字符串,searchValue 會被強制設置為 “undefined”, 然後在當前字符串中查找這個值。
舉個例子:’undefined’.indexOf() 將會返回0,因為 undefined 在位置0處被找到,但是 ‘undefine’.indexOf() 將會返回 -1 ,因為字符串 ‘undefined’ 未被找到。
fromIndex 可選
數字表示開始查找的位置。可以是任意整數,默認值為 0。
如果 fromIndex 的值小於 0,或者大於 str.length ,那麼查找分別從 0 和str.length 開始。
舉個例子,’hello world’.indexOf(‘o’, -5) 返回 4 ,因為它是從位置0處開始查找,然後 o 在位置4處被找到。另一方面,’hello world’.indexOf(‘o’, 11) (或 fromIndex 填入任何大於11的值)將會返回 -1 ,因為開始查找的位置11處,已經是這個字符串的結尾了。
示例
var anyString = "Brave new world";
console.log("The index of the first w from the beginning is " + anyString.indexOf("w"));
// logs 8
console.log("The index of the first w from the end is " + anyString.lastIndexOf("w"));
// logs 10
console.log("The index of 'new' from the beginning is " + anyString.indexOf("new"));
// logs 6
console.log("The index of 'new' from the end is " + anyString.lastIndexOf("new"));
// logs 6
原創文章,作者:投稿專員,如若轉載,請註明出處:https://www.506064.com/zh-hk/n/269349.html
微信掃一掃
支付寶掃一掃