通常、私はメソッドを期待しますが、String.contains()
メソッドがないようです。
これを確認する合理的な方法は何ですか?
通常、私はメソッドを期待しますが、String.contains()
メソッドがないようです。
これを確認する合理的な方法は何ですか?
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
String.prototype.includes
ES6にはあります:
"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;
}
};
}