2016-04-12 82 views

回答

24

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具有使用indexOfincludes一個填充工具:https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/String/includes#Polyfill

+0

在Opera 46.0它的工作原理 –

6

包括()不被大多數瀏覽器支持。你的選擇是要麼使用

從MDN -polyfill https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/String/includes

或使用

-indexof()

var str = "abcde"; 
var n = str.indexOf("cd"); 

它給你N = 2

這是廣泛支持。

+0

這個正確答案。使用來自MDN的聚合物 – Sangar82

+0

如果您使用MDN中的polyfill,_do不會用'for ... in'!_來迭代您的字符串,如果您像這樣定義它,它將遍歷'String.prototype.includes'。 –

5

或者只是把這個JavaScript文件中,有一個美好的一天:)

String.prototype.includes = function (str) { 
    var returnValue = false; 

    if (this.indexOf(str) !== -1) { 
    returnValue = true; 
    } 

    return returnValue; 
} 
+0

如果你使用這個polyfill,不要用'for ... in'迭代你的字符串,如果它是這樣定義的,它將遍歷'String.prototype.includes'。 –

0

如果你想使用Array.prototype.include()在JavaScript中,你可以使用這個腳本來保持: github-script-ie-include ,自動將包括轉換()匹配()函數,如果它檢測到IE。

其他選項始終使用string.match(Regex(expression))

相關問題