我有以下几点:
if (referrer.indexOf("Ral") == -1) { ... }
我喜欢做的是使Ral不区分大小写,这样它可以是Ral, Ral等,仍然匹配。
有办法说拉尔必须不区分大小写吗?
我有以下几点:
if (referrer.indexOf("Ral") == -1) { ... }
我喜欢做的是使Ral不区分大小写,这样它可以是Ral, Ral等,仍然匹配。
有办法说拉尔必须不区分大小写吗?
当前回答
这里有几种方法。
如果您希望仅对该实例执行不区分大小写的检查,请执行如下操作。
if (referrer.toLowerCase().indexOf("Ral".toLowerCase()) == -1) {
...
或者,如果定期执行这种检查,可以向String添加一个新的类似indexOf()的方法,但要使其不区分大小写。
String.prototype.indexOfInsensitive = function (s, b) {
return this.toLowerCase().indexOf(s.toLowerCase(), b);
}
// Then invoke it
if (referrer.indexOfInsensitive("Ral") == -1) { ...
其他回答
在referrer后添加. touppercase()。此方法将字符串转换为大写字符串。然后,使用. indexof()使用RAL代替RAL。
if (referrer.toUpperCase().indexOf("RAL") === -1) {
使用正则表达式也可以达到同样的效果(当你想测试动态模式时特别有用):
if (!/Ral/i.test(referrer)) {
// ^i = Ignore case flag for RegExp
另一种选择是使用如下的搜索方法:
if (referrer.search(new RegExp("Ral", "i")) == -1) { ...
它看起来比将整个字符串转换为小写更优雅,而且可能更高效。 使用toLowerCase()代码对字符串进行了两次传递,一次是对整个字符串进行传递,将其转换为小写,另一次是寻找所需的索引。 在RegExp中,代码只传递一次字符串,以便与所需的索引匹配。
因此,对于长字符串,我建议使用RegExp版本(我猜对于短字符串,这种效率来自于创建RegExp对象)
如果referrer是一个数组,则可以使用findIndex()
if(referrer.findIndex(item => 'ral' === item.toLowerCase()) == -1) {...}
你可以试试这个
str = "哇,太酷了" searchStr = "CoOl" console.log (str.toLowerCase()其中包括(searchStr.toLowerCase ()))
现在都2016年了,还没有明确的方法来做到这一点吗?我还想要复印的呢。我来试试。
设计说明:我想尽量减少内存使用,从而提高速度——这样就不会复制/改变字符串。我认为V8(和其他引擎)可以优化这个功能。
//TODO: Performance testing
String.prototype.naturalIndexOf = function(needle) {
//TODO: guard conditions here
var haystack = this; //You can replace `haystack` for `this` below but I wan't to make the algorithm more readable for the answer
var needleIndex = 0;
var foundAt = 0;
for (var haystackIndex = 0; haystackIndex < haystack.length; haystackIndex++) {
var needleCode = needle.charCodeAt(needleIndex);
if (needleCode >= 65 && needleCode <= 90) needleCode += 32; //ToLower. I could have made this a function, but hopefully inline is faster and terser
var haystackCode = haystack.charCodeAt(haystackIndex);
if (haystackCode >= 65 && haystackCode <= 90) haystackCode += 32; //ToLower. I could have made this a function, but hopefully inline is faster and terser
//TODO: code to detect unicode characters and fallback to toLowerCase - when > 128?
//if (needleCode > 128 || haystackCode > 128) return haystack.toLocaleLowerCase().indexOf(needle.toLocaleLowerCase();
if (haystackCode !== needleCode)
{
foundAt = haystackIndex;
needleIndex = 0; //Start again
}
else
needleIndex++;
if (needleIndex == needle.length)
return foundAt;
}
return -1;
}
我取这个名字的原因:
应该有IndexOf的名字 不要添加后缀词—IndexOf指的是下面的参数。所以用前缀代替。 不要使用“大小写不敏感”前缀会太长 “natural”是一个很好的候选词,因为默认区分大小写的比较首先对人类来说并不自然。
为什么不…:
toLowerCase() -可能重复调用同一个字符串上的toLowerCase。 RegExp—用变量搜索很麻烦。甚至RegExp对象也不得不转义字符