Reputation: 809
I'm just trying to ignore case when doing a search what's the best way to do it? (No Jquery please)
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. So any suggestions? I want to ignore the case of photoData's description
Upvotes: 0
Views: 584
Reputation: 1505
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;
}
Upvotes: 0
Reputation: 50905
Create a new RegExp
and use the case-insensitive flag, like:
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/
Although you can use the Array.filter
method also:
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/
Reference:
Array.filter
: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filterRegExp
: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp#ParametersUpvotes: 3
Reputation: 819
As long as you're not dealing with Unicode characters (as some case conversions work unexpectedly in some Unicode supported languages), do this:
if (photoData[i].description.toUpperCase() === searchValue.toUpperCase()) {
your code
}
or you could use toLowerCase...
Upvotes: 1