在chrome中工作时,string.contains()不存在

meh*_*dvd 14 javascript google-chrome

我有一个代码:

var valid = viewName.contains('/');
Run Code Online (Sandbox Code Playgroud)

在firefox浏览器中工作正常.但在铬合金中它是undefined.为什么会这样?是不是铬没有这种字符串的方法?

是否确定要使用indexOf的替代contains,是它在所有的浏览器都支持?

Raj*_*esh 39

String.contains()的浏览器兼容性

String.indexOf() 是我用的,它会工作正常.

  var strIndex = viewName.indexOf('/');
  if(strIndex == -1) {
     //string not found
  } else {
    //string found
  }
Run Code Online (Sandbox Code Playgroud)

但是,如果你想要一个contains()功能,你可以添加String如下:

 if(!('contains' in String.prototype)) {
       String.prototype.contains = function(str, startIndex) {
                return -1 !== String.prototype.indexOf.call(this, str, startIndex);
       };
 }

var valid = viewName.contains('/');
if(valid) {
  //string found
} else {
  //string not found
}
Run Code Online (Sandbox Code Playgroud)

  • 仅供参考:ES6 草案标准将`.contains()` 更改为`.includes()` `.contains()` 最终将从Firefox 中删除并替换为标准的`.includes`。目前 Chrome 提供了 `.includes`。 (2认同)
  • 在添加答案时,并非所有浏览器都原生支持 contains (2认同)

Gra*_*Fox 7

现在,默认情况下也禁用Firefox和Chrome中对此功能的支持。如果你的土地在这里寻找一个最新的回答,您可以查看的原因所在,而新方法的名称(这是String.includes在这里

尝试:

yourString.includes('searchString')