--- title: String.prototype.includes() slug: Web/JavaScript/Reference/Global_Objects/String/includes tags: - JavaScript - Method - Prototype - Reference - String translation_of: Web/JavaScript/Reference/Global_Objects/String/includes ---
{{JSRef}}

includes() メソッドは、1 つの文字列を別の文字列の中に見出すことができるかどうかを判断し、必要に応じて truefalse を返します。

{{EmbedInteractiveExample("pages/js/string-includes.html", "shorter")}}

構文

str.includes(searchString[, position])

引数

searchString
str 内で検索される文字列。
position {{optional_inline}}
文字列内で searchString を検索し始める位置。既定値は 0 です。

返値

文字列が検索値を含む場合、true。含まなければ、false

解説

このメソッドによってある文字列内に別の文字列を含んでいるかどうか判断できます。

大文字・小文字の区別

includes() メソッドは大文字と小文字が区別します。例えば、次のコードでは false を返します:

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

includes()を使う

const 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
console.log(str.includes(''))             // true

ポリフィル

このメソッドは ECMAScript 2015 で追加されました。まだ、すべての JavaScript の実装で利用できるとは限りません。

しかしながら、このメソッドを簡単にエミュレートできます。

if (!String.prototype.includes) {
  String.prototype.includes = function(search, start) {
    'use strict';

    if (search instanceof RegExp) {
      throw TypeError('first argument must not be a RegExp');
    }
    if (start === undefined) { start = 0; }
    return this.indexOf(search, start) !== -1;
  };
}

仕様書

仕様書
{{SpecName('ESDraft', '#sec-string.prototype.includes', 'String.prototype.includes')}}

ブラウザーの互換性

{{Compat("javascript.builtins.String.includes")}}

String.prototype.contains

Firefox 18–39 では、このメソッドの名称は contains() でした。以下の理由により、 bug 1102219includes() に名称が変更されました。

報告されたところによると、 MooTools 1.2 を使用したいくつかのウェブサイトが Firefox 17 で壊れました。この版の MooTools は、 String.prototype.contains() が存在するかどうか調べ、存在しない場合は MooTools が独自の関数を追加するようになっています。

この関数が Firefox 17 で導入されたことで、このチェックの動作が変わり、 MooTools の String.prototype.contains() の実装に基づくコードが壊れることになりました。結果的に、 Firefox 17 では実装が無効化され、 String.prototype.contains() が利用できるようになったのは一つ後のバージョンである Firefox 18 で、 MooTools への働きかけによって MooTools バージョン 1.2.6 がリリースされてからでした。

MooTools 1.3 では String.prototype.contains() を強制的に自分自身のものに強制したため、これに依存するウェブサイトは壊れません。しかし、このメソッドに対する MooTools 1.3 のシグニチャ と ECMAScript 2015 のシグニチャでは (第 2 引数に) 違いがあることに注意して下さい。後に、 MooTools 1.5 以降で ES2015 仕様に一致させるためにシグニチャを変更しました。

Firefox 48 で、String.prototype.contains() は削除されました。 String.prototype.includes() だけを使用してください。

関連情報