[英]Ignore case when searching an Array in javascript
I'm just trying to ignore case when doing a search what's the best way to do it? 我只是想在进行搜索时忽略大小写,最好的方法是什么? (No Jquery please)
(请不要使用Jquery)
function search(searchValue) {
var found = [];
for (var i = 0; i < photoData.length; i++) {
if (photoData[i].description.search(searchValue) != -1) {
found.push(photoData[i]);
}
}
console.log(found);
return found;
}
I tried doing search(searchValue.ignoreCase)
but it returns duplicates of any that have an uppercase letter. 我尝试执行
search(searchValue.ignoreCase)
但是它返回任何具有大写字母的重复项。 So any suggestions? 有什么建议吗? I want to ignore the case of photoData's description
我想忽略photoData描述的情况
Create a new RegExp
and use the case-insensitive flag, like: 创建一个
new RegExp
并使用不区分大小写的标志,例如:
function search(array, searchValue) {
var matchedValues, re, i, j, cur;
matchedValues = [];
re = new RegExp(searchValue, "i");
for (i = 0, j = array.length; i < j; i++) {
cur = array[i];
if (cur.description.search(re) !== -1) {
matchedValues.push(cur);
}
}
return matchedValues;
}
DEMO: http://jsfiddle.net/7veds/ 演示: http : //jsfiddle.net/7veds/
Although you can use the Array.filter
method also: 尽管还可以使用
Array.filter
方法:
function search(array, searchValue) {
var re = new RegExp(searchValue, "i");
return array.filter(function (item, idx) {
return item.description.search(re) !== -1;
});
}
DEMO: http://jsfiddle.net/TKphp/ 演示: http : //jsfiddle.net/TKphp/
Reference: 参考:
Array.filter
: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter Array.filter
: https : //developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Array/filter RegExp
: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp#Parameters RegExp
: https : //developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/RegExp#Parameters As long as you're not dealing with Unicode characters (as some case conversions work unexpectedly in some Unicode supported languages), do this: 只要您不处理Unicode字符(某些情况下转换在某些Unicode支持的语言中意外地起作用),请执行以下操作:
if (photoData[i].description.toUpperCase() === searchValue.toUpperCase()) {
your code
}
or you could use toLowerCase... 或者您可以使用toLowerCase ...
here is a small snippet from Case insensitive search in array 这是数组中不区分大小写的搜索的一小段
function SearchArray( element, array ) {
var len = array.length, str = element.toString().toLowerCase();
for ( var i = 0; i < len; i++ ) {
if ( array[i].toLowerCase() == str ) { return i; }
}
return -1;
} }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.