7417

通常、私はメソッドを期待しますが、String.contains()メソッドがないようです。

これを確認する合理的な方法は何ですか?

4

3 に答える 3

15103

ECMAScript 6 の導入String.prototype.includes:

const string = "foo";
const substring = "oo";

console.log(string.includes(substring)); // true

includes ただし、 Internet Explorer のサポートはありません。ECMAScript 5 以前の環境ではString.prototype.indexOf、部分文字列が見つからない場合に -1 を返す を使用します。

var string = "foo";
var substring = "oo";

console.log(string.indexOf(substring) !== -1); // true

于 2009-11-24T13:05:36.550 に答える
716

String.prototype.includesES6にはあります

"potato".includes("to");
> true

これは Internet Explorer や、 ES6 のサポートがない、または不完全なその他の古いブラウザーでは機能しないことに注意してください。古いブラウザーで動作させるには、Babelのようなトランスパイラー、 es6-shimのような shim ライブラリ、またはMDNのこのポリフィルを使用することをお勧めします。

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;
    }
  };
}
于 2013-01-07T10:23:16.590 に答える