2016-04-12 83 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))

相关问题