Originally, problem is that I must get some notification, when term (city name in project), entered by user in JqueryUI Autocomplete not matching with anything in collection (entered "My Sweet City" and it doesn't match [Moscow, New-York, Beijing]). So I will rewrite my code to manually search in array, but I have one question — how search in array like autocomplete it doing?
-
possible duplicate of Javascript - search for a string inside an array of stringsJJJ– JJJ2015-07-20 16:44:50 +00:00Commented Jul 20, 2015 at 16:44
-
possible duplicate of Javascript array search and remove string?Jason Cust– Jason Cust2015-07-20 16:45:39 +00:00Commented Jul 20, 2015 at 16:45
Add a comment
|
1 Answer
There are a couple of ways to do this. If it's something simple, you can get away with using indexOf to find a match like so:
var arr = ["one", "two", "three", "four", "five"];
var inputText = "three";
if (arr.indexOf(inputText) > -1) {
alert("item found");
}
else {
alert("item not found");
}
Another option (and more efficient option), would be to use a regular explression and cycle through the array to find matches (mentioned by Aleadam):
function searchStringInArray (str, strArray) {
for (var j=0; j<strArray.length; j++) {
if (strArray[j].match(str)) return j;
}
return -1;
}