gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 01:35:36 25 4
gpt4 key购买 nike

我有这样的代码:

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com