回答:
String.prototype.includes
あなたが書いているように、Internet Explorer(またはOpera)ではサポートされていません。
代わりにを使用できますString.prototype.indexOf
。#indexOf
文字列内にある場合は部分文字列の最初の文字のインデックスを返し、それ以外の場合はを返します-1
。(配列同等のものと非常に似ています)
var myString = 'this is my string';
myString.indexOf('string');
// -> 11
myString.indexOf('hello');
// -> -1
MDNは用ポリフィル持ってincludes
使用してindexOf
:https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/String/includes#Polyfill
編集:Opera includes
はバージョン28からサポートしています。
編集2:Edgeの現在のバージョンはこの方法をサポートしています。(2019年現在)
Boolean
、次のことができます(myString.indexOf('string') > -1) // to get a boolean true or false
または、これをJavascriptファイルに入れて、良い一日を:)
String.prototype.includes = function (str) {
var returnValue = false;
if (this.indexOf(str) !== -1) {
returnValue = true;
}
return returnValue;
}
for...in
で反復しないでくださいString.prototype.includes
。このように定義されている場合は、反復されます。
return this.indexOf(str) !== -1;
contains()は、ほとんどのブラウザでサポートされていません。あなたのオプションはどちらかを使用することです
-MDNのpolyfill https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/String/includes
または使用する
-の指標()
var str = "abcde";
var n = str.indexOf("cd");
それはあなたにn = 2を与えます
これは広くサポートされています。
for...in
!で文字列を反復しないでください。、そのString.prototype.includes
ように定義すると、繰り返し処理されます。
問題:
Internet Explorerから以下(ソリューションなし)を実行してみて、結果を確認してください。
console.log("abcde".includes("cd"));
解決:
ソリューションの下で実行して結果を確認してください
if (!String.prototype.includes) {//To check browser supports or not
String.prototype.includes = function (str) {//If not supported, then define the method
return this.indexOf(str) !== -1;
}
}
console.log("abcde".includes("cd"));
Array.prototype.include()
JavaScriptで引き続き使用したい場合は、次のスクリプトを使用できます
。github-script-ie-include
IEを検出すると、include()をmatch()関数に自動的に変換します。
他のオプションは常に使用していますstring.match(Regex(expression))
あなたは同じことをすることができます!! および〜演算子
var myString = 'this is my string';
!!~myString.indexOf('string');
// -> true
!!~myString.indexOf('hello');
// -> false
2つの演算子(!!と〜)の説明は次のとおりです
https://www.joezimjs.com/javascript/great-mystery-of-the-tilde/