2012-01-24 128 views
279

我有以下几点:的Javascript包含大小写不敏感

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

我喜欢做的事情就是让Ral区分大小写的,所以它可以RAlrAl等,仍然匹配。

有没有办法说Ral必须不区分大小写?

+3

我认为不区分大小写的正则表达式是更优雅的解决方案,但每个人都应该牢记直接从用户输入创建“RegExp”的缺陷。例如,用户可以输入'*',并在'RegExp'构造函数中抛出错误。接受的解决方案没有这个问题。 – pllee

+1

[indexOf区分大小写?]的可能重复(http://stackoverflow.com/questions/1126227/indexof-case-sensitive) – HadiRj

回答

416

添加.toLowerCase()referrer。此方法将字符串转换为小写字符串。然后,使用.indexOf()而不是Ral

if (referrer.toLowerCase().indexOf("ral") === -1) { 

同样也可以使用正则表达式(尤其是有用的,当你想测试对动态模式)来实现:

if (!/Ral/i.test(referrer)) { 
    // ^i = Ignore case flag for RegExp 
+13

后一种方法更正确;前者将失败的土耳其我和任何其他这样的有问题的大写/小写对:http://www.i18nguy.com/unicode/turkish-i18n.html – Domenic

+15

对于土耳其语,最好使用'toLocaleLowerCase()' ([ref](https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/String/toLocaleLowerCase)) – Mottie

+2

后者不回答这个问题,它只是说如果它存在,没有得到匹配的索引。问题标题是错误的还是问题。 – Maslow

4
if (referrer.toUpperCase().indexOf("RAL") == -1) { ... 
+1

-1,http:// www.i18nguy.com/unicode/turkish-i18n.html – Domenic

+3

@Domenic +1这个答案,不会有动态输入的正则表达式元字符问题,这是一个更可能的问题。 -1到所有其他答案。 –

+0

toLowerCase()是更稳健的解决方案,因为在大写情况下可能会出现无法比较ASC2符号的问题。 –

18

使用正规:

if (!/ral/i.test(referrer)) { 
    ... 
} 

或使用.toLowerCase()

if (referrer.toLowerCase().indexOf("ral") == -1) 
+1

+1,通过避免“土耳其我的问题”和其他类似的陷阱,这可能会更准确:http://www.i18nguy.com/unicode/turkish-i18n.html – Domenic

+0

如果“ral”是动态的,那么必须转换为小写。 – Kurkula

9

这里有几种方法。

如果您想对此实例执行不区分大小写检查,请执行以下操作。

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

或者,如果你经常进行此项检查,你可以添加一个新indexOf()样的方法来String,但要区分大小写。

String.prototype.indexOfInsensitive = function (s, b) { 
    return this.toLowerCase().indexOf(s.toLowerCase(), b); 
} 

// Then invoke it 
if (referrer.indexOfInsensitive("Ral") == -1) { ... 
+0

如果您扩展原型并使用'indexOf'的特定实现,请不要忘记可选的第二个参数:起始位置(''a a'.indexOf('a',1)=== 2')。 –

+0

@RobW好的呼叫;修正。 – cheeken

+1

对于支持['defineProperty'](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object/defineProperty)的现代浏览器,我建议'Object.defineProperty(String.prototype,'indexOfInsensitive', {value:function(s,b){return this.toLowerCase()。indexOf((s +'')。toLowerCase(),b);}});'。两个更新:使用'(s +'')'显式字符串转换,以及循环中的不可枚举('for(var i in'')...'不显示'indexOfInsensitive'。 –

1

要做到更好的搜索使用下面的代码,

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())); 

在第一个警报(),JavaScript的返回 “-1” - 换句话说,的indexOf()没有找到匹配:这仅仅是因为“JavaScript”在第一个字符串中是小写字母,而在第二个字符串中恰当地大写。要使用indexOf()执行不区分大小写的搜索,可以使两个字符串都为大写或小写。这意味着,与第二个alert()中一样,JavaScript只会检查您正在查找的字符串的出现,忽略大小写。

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

67

另一个选项是使用搜索方法如下:

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

它看起来更优雅然后转换整个字符串小写并且它可以是更有效的。
With toLowerCase()该代码有两个字符串传递,一个传递是在整个字符串将其转换为小写字母,另一个是寻找所需的索引。
RegExp该代码有一个通过字符串,它看起来匹配所需的索引。

因此,对长字符串,我建议使用RegExp版本(我想这对短字符串这个效率自带的帐户创建尽管RegExp对象)

+7

+1,此解决方案允许表达式被存储在一个变量中 –

+1

这更接近于答案,因为通过测试或匹配你不能得到索引 – FlavorScape

+1

根据我的测试,这也相当快一些:http://jsperf.com/case-insensitive-indexof –

1

这是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在名称
  • 不要添加一个后缀 - 是指下列参数
  • 不要使用“CASEINSENSITIVE “这太长了
  • ”自然“是一个很好的选择,因为默认的区分大小写的比较首先不是人类自然选择的。

为什么不...:

  • toLowerCase() - 在相同的字符串潜在重复调用toLowerCase。
  • RegExp - 用变量搜索很难。即使是RegExp对象的尴尬不必转义字符
+0

呼吸新鲜空气有人真的花时间思考并解释他们功能名称的推理,你已经让世界在那里一个更好的地方。 –

0

这是我的看法:

脚本

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:

<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