字符串包含不在IE中工作

时间:2014-11-03 17:57:11

标签: javascript internet-explorer

我正在尝试使用contains来查找字符串中是否出现短语 以下代码在FF和Chrome中运行良好,但IE8-10会返回错误。

  

SCRIPT438:对象不支持属性或方法'contains'

var str = "This is a string";
if(str.contains("string")){
    alert('Yes'};
}

不确定为什么IE会抛出错误,所以任何帮助都会非常感激。

1 个答案:

答案 0 :(得分:9)

.contains()功能是旧版Internet Explorer版本不支持的ES2015功能。

MDN page有一个polyfill:

if ( !String.prototype.contains ) {
    String.prototype.contains = function() {
        return String.prototype.indexOf.apply( this, arguments ) !== -1;
    };
}

此类问题的一般指南:在Google搜索框中输入MDN something。如果你没有找到结果,那么"某事"可能并不存在于JavaScript Universe中。如果你这样做,那么你很有可能找到你在那里寻找的答案。