在chrome中工作时string.contains()不存在 [英] string.contains() doesn't exist while working in chrome

查看:249
本文介绍了在chrome中工作时string.contains()不存在的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的代码:

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

在Firefox浏览器中正常工作。但是在chrome中它是 undefined 。为什么?是不是真的,铬没有这样的字符串的方法?



可以使用 indexOf 而不是包含,是否在所有浏览器中都支持?

解决方案



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

  var strIndex = viewName.indexOf( '/'); 
if(strIndex == -1){
//找不到字符串
} else {
//找到字符串
}


但是,如果你想要一个 contains()函数,你可以将它添加到 String 如下:

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

var valid = viewName.contains('/');
if(valid){
//找到字符串
} else {
//字符串未找到
}


I have a code like:

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

which works fine in firefox browser. But in chrome it is undefined. Why is that so? Is it true that chrome has not such a method for string?

Is it OK to use indexOf instead of contains, is it supported in all browsers?

解决方案

String.indexOf() is what I use and it will work fine.

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

But, just in case you want to have a contains() function, you can add it to String as below:

 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
}

这篇关于在chrome中工作时string.contains()不存在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆