String.prototype.includes()

includes()方法判断一个字符串是否包含在另一个字符串中,根据情况返回true或false。

这是一个ES6方法。

searchString

要搜索的字符串。

position

可选。从当前字符串的哪个索引位置开始搜寻子字符串;默认值为0。

如果当前字符串包含被搜寻的字符串,就返回true;否则,返回false。

includes() 方法是区分大小写的。

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'));       // 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;
    }
  };
}

 

posted @ 2018-06-26 21:56  hahazexia  阅读(681)  评论(0)    收藏  举报