Please note, this is a STATIC archive of website developer.mozilla.org from 03 Nov 2016, cach3.com does not collect or store any user information, there is no "phishing" involved.

String.prototype.includes()

这篇翻译不完整。请帮忙从英语翻译这篇文章

includes() 方法用于判断一个字符串是否被包含在另一个字符串中,如果是返回true,否则返回false。

语法

str.includes(searchString[, position])

参数

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

描述

这个方法可以帮你确定一个字符串是否包含另外一个字符串。

区分大小写

includes() 是区分大小写的。例如,下面的表达式返回 false

'Blue Whale'.includes('blue'); // returns false

例子

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

这个方法已经被加入到 ECMAScript 6 标准中,但未必在所有的 JavaScript 实现中都可以使用。下面的一个简单的 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;
    }
  };
}

Specifications

Specification Status Comment
ECMAScript 2015 (6th Edition, ECMA-262)
String.prototype.includes
Standard Initial definition.
ECMAScript 2017 Draft (ECMA-262)
String.prototype.includes
Draft  

浏览器兼容性

Feature Chrome Firefox (Gecko) Internet Explorer Opera Safari
Basic support 41 40 (40) 未实现 未实现 9
Feature Android Chrome for Android Firefox Mobile (Gecko) IE Mobile Opera Mobile Safari Mobile
Basic support 未实现 未实现 40.0 (40) 未实现 未实现 未实现

String.prototype.contains

In Firefox 18 - 39, the name of this method was contains(). It was renamed to includes() in bug 1102219 due to the following reason:

It's been reported that some websites using MooTools 1.2 broke on Firefox 17. This version of MooTools checks whether String.prototype.contains() exists and, if it doesn't,  MooTools adds its own function. With the introduction of this function in Firefox 17, the behavior of that check changed in a way that causes code based on MooTools' String.prototype.contains() implementation to break. As a result, the implementation was disabled in Firefox 17 and String.prototype.contains() was available one version later, in Firefox 18, when outreach to MooTools was leading to the release of MooTools version 1.2.6.

MooTools 1.3 forces its own version of String.prototype.contains(), so websites relying on it should not break. However, you should note that MooTools 1.3 signature and ECMAScript 6 signatures for this method differ (on the second argument). Later, MooTools 1.5+ changed the signature to match the ES6 standard.

See also

文档标签和贡献者

 此页面的贡献者: zilong-thu, teoli, ziyunfei
 最后编辑者: zilong-thu,