[英]Contains case insensitive
我有以下內容:
if (referrer.indexOf("Ral") == -1) { ... }
我喜歡做的是讓Ral
不區分大小寫,這樣它就可以是rAl
RAl
並且仍然匹配。
有沒有辦法說Ral
必須不區分大小寫?
在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
對象的原因)
從 ES2016 開始,您還可以使用稍微更好/更簡單/更優雅的方法(區分大小寫):
if (referrer.includes("Ral")) { ... }
或(不區分大小寫):
if (referrer.toLowerCase().includes(someString.toLowerCase())) { ... }
以下是.indexOf()
和.includes()
的一些比較: https ://dev.to/adroitcoder/includes-vs-indexof-in-javascript
使用正則表達式:
if (!/ral/i.test(referrer)) {
...
}
或者,使用.toLowerCase()
:
if (referrer.toLowerCase().indexOf("ral") == -1)
這里有幾種方法。
如果您只想對此實例執行不區分大小寫的檢查,請執行以下操作。
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) { ...
你可以試試這個
str = "Wow its so COOL" searchStr = "CoOl" console.log(str.toLowerCase().includes(searchStr.toLowerCase()))
任何語言的示例:
'My name is Хведор'.toLocaleLowerCase().includes('ХвЕдОр'.toLocaleLowerCase())
以下是 ES6 中按性能降序排列的選項
包括
if (referrer.toLowerCase().includes("Ral".toLowerCase())) { ... }
IndexOf(這有時會產生與 Includes 相似或更好的結果)
if (referrer.toLowerCase().indexOf("Ral".toLowerCase()) !== -1) { ... }
匹配
if (referrer.match(new RegExp("Ral", 'i'))) { ... }
基准測試結果: https ://jsben.ch/IBbnl
if (referrer.toUpperCase().indexOf("RAL") == -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() ) );
在第一個 alert() 中,JavaScript 返回“-1” - 換句話說, indexOf() 沒有找到匹配項:這僅僅是因為“JavaScript”在第一個字符串中是小寫的,而在第二個字符串中正確大寫。 要使用 indexOf() 執行不區分大小寫的搜索,您可以將兩個字符串都設為大寫或小寫。 這意味着,就像在第二個 alert() 中一樣,JavaScript 只會檢查您要查找的字符串是否出現,忽略大小寫。
參考,http: //freewebdesigntutorials.com/javaScriptTutorials/jsStringObject/indexOfMethod.htm
現在是 2016 年,沒有明確的方法可以做到這一點嗎? 我希望有一些copypasta。 我會去的。
設計說明:我想盡量減少內存使用,從而提高速度 - 所以沒有字符串的復制/變異。 我假設 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;
}
我取這個名字的原因:
為什么不...:
toLowerCase()
- 對同一字符串的潛在重復調用 toLowerCase。RegExp
- 使用變量搜索很尷尬。 即使是 RegExp 對象也很尷尬,不得不轉義字符如果referrer
是一個數組,你可以使用findIndex()
if(referrer.findIndex(item => 'ral' === item.toLowerCase()) == -1) {...}
這是我的看法:
腳本:
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>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.