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

标签 javascript google-chrome

我有这样的代码:

var valid = viewName.contains('/');

在 firefox 浏览器中运行良好。但在 chrome 中它是 undefined。为什么?难道chrome没有这样的string方法吗?

是否可以使用 indexOf 而不是 contains,所有浏览器都支持它吗?

最佳答案

Browser compatibility of String.contains()

String.indexOf() 是我使用的,它可以正常工作。

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

但是,以防万一你想要一个 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
}

关于javascript - 在 chrome 中工作时 string.contains() 不存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19196337/

相关文章:

javascript - 如何在 Babylon.js 中为形状着色?

google-chrome - 如何取消缩放 Chrome-* 控制台

javascript - 如何在 Chrome DevTools 中运行自定义代码?

php - Google 验证码未在 GoDaddy 安全 (https) 中显示

javascript - 您可以在不使用服务器的情况下在本地生成 html 吗?

javascript - 除了第一次,jQuery 对象永远不会改变

javascript - jQuery 总是选中一个复选框

javascript - Angular Batarang 适用于不使用 ng-app 的应用

javascript - 在 Chrome 中选择文本节点的开始

javascript - 关闭 Chrome 中的弹出窗口似乎不会释放内存