包含不区分大小写的

本文翻译自:Contains case insensitive

I have the following: 我有以下内容:

if (referrer.indexOf("Ral") == -1) { ... }

What I like to do is to make Ral case insensitive, so that it can be RAl , rAl , etc. and still match. 我喜欢做的是让Ral区分大小写的,所以它可以RAlrAl等,仍然匹配。

Is there a way to say that Ral has to be case-insensitive? 有没有办法说Ral必须不区分大小写?


#1楼

参考:https://stackoom.com/question/bjgr/包含不区分大小写的


#2楼

To do a better search use the following code, 为了更好地进行搜索,请使用以下代码,

var myFav   = "javascript";
var theList = "VB.NET, C#, PHP, Python, JavaScript, and Ruby";

// Check for matches with the plain vanilla indexOf() method:
alert( theList.indexOf( myFav ) );

// Now check for matches in lower-cased strings:
alert( theList.toLowerCase().indexOf( myFav.toLowerCase() ) );

In the first alert(), JavaScript returned "-1" - in other words, indexOf() did not find a match: this is simply because "JavaScript" is in lowercase in the first string, and properly capitalized in the second. 在第一个alert()中,JavaScript返回“ -1”-换句话说,indexOf()找不到匹配项:这仅仅是因为“ JavaScript”在第一个字符串中小写,而在第二个字符串中大写。 To perform case-insensitive searches with indexOf(), you can make both strings either uppercase or lowercase. 要使用indexOf()执行不区分大小写的搜索,可以将两个字符串都设置为大写或小写。 This means that, as in the second alert(), JavaScript will only check for the occurrence of the string you are looking for, capitalization ignored. 这意味着,与第二个alert()一样,JavaScript将仅检查您要查找的字符串的出现,忽略大小写。

Reference, http://freewebdesigntutorials.com/javaScriptTutorials/jsStringObject/indexOfMethod.htm 参考, http://freewebdesigntutorials.com/javaScriptTutorials/jsStringObject/indexOfMethod.htm


#3楼

Another options is to use the search method as follow: 另一种选择是使用搜索方法,如下所示:

if (referrer.search(new RegExp("Ral", "i")) == -1) { ...

It looks more elegant then converting the whole string to lower case and it may be more efficient. 然后看起来很优雅,然后将整个字符串转换为小写字母,这样可能会更有效率。
With toLowerCase() the code have two pass over the string, one pass is on the entire string to convert it to lower case and another is to look for the desired index. 使用toLowerCase() ,代码对字符串进行了两次遍历,一次遍历是整个字符串将其转换为小写,另一遍是查找所需的索引。
With RegExp the code have one pass over the string which it looks to match the desired index. 使用RegExp ,代码可以遍历看起来与所需索引匹配的字符串。

Therefore, on long strings I recommend to use the RegExp version (I guess that on short strings this efficiency comes on the account of creating the RegExp object though) 因此,在长字符串上,我建议使用RegExp版本(我想在短字符串上,这种效率取决于创建RegExp对象)


#4楼

It's 2016, and there's no clear way of how to do this? 现在是2016年,没有明确的方法来做到这一点? I was hoping for some copypasta. 我希望有一些复制。 I'll have a go. 我去吧

Design notes: I wanted to minimize memory usage, and therefore improve speed - so there is no copying/mutating of strings. 设计说明:我想最大程度地减少内存使用量,从而提高速度-因此不存在字符串的复制/变异。 I assume V8 (and other engines) can optimise this function. 我认为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;
}

My reason for the name: 我名字的原因:

  • Should have IndexOf in the name 名称中应具有IndexOf
  • Don't add a suffix - Of refers to the following parameter 不添加后缀-Of表示以下参数
  • Don't use "caseInsensitive" that's sooooo long 不要使用太长的“ caseInsensitive”
  • "natural" is a good candidate, because default case sensitive comparisons are not natural to humans in the first place. “自然”是一个不错的选择,因为默认情况下区分大小写的比较一开始就不自然。

Why not...: 为什么不...:

  • toLowerCase() - potential repeated calls to toLowerCase on the same string. toLowerCase() -可能在同一字符串上重复调用toLowerCase。
  • RegExp - awkward to search with variable. RegExp难以搜索变量。 Even the RegExp object is awkward having to escape characters 甚至RegExp对象也难以转义字符

#5楼

Here's my take: 这是我的看法:

Script : 剧本

var originalText = $("#textContainer").html()
$("#search").on('keyup', function () {
  $("#textContainer").html(originalText)
  var text = $("#textContainer").html()
  var val = $("#search").val()
  if(val=="") return;
  var matches = text.split(val)
  for(var i=0;i<matches.length-1;i++) {
    var ind =  matches[i].indexOf(val)
    var len = val.length
      matches[i] = matches[i] + "<span class='selected'>" + val + "</span>"
  }
  $("#textContainer").html(matches.join(""))

HTML: HTML:

<input type="text" id="search">
<div id="textContainer">
lorem ipsum is simply dummy text of the printing and typesetting industry. lorem ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of letraset sheets containing lorem ipsum passages, and more recently with desktop publishing software like Aldus pagemaker including versions of lorem ipsum.</div>

Codepen 码笔


#6楼

From ES2016 you can also use slightly better / easier / more elegant method: 从ES2016起,您还可以使用稍微更好/更容易/更优雅的方法:

if (referrer.includes("Ral")) { ... }

or 要么

if (referrer.toLowerCase().includes(someString.toLowerCase())) { ... }

Here is some comparison of .indexOf() and .includes() : https://dev.to/adroitcoder/includes-vs-indexof-in-javascript 这是.indexOf().includes()一些比较: https : .indexOf()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值