-3

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?

Arman Hayots
  • 2,459
  • 6
  • 29
  • 53
  • possible duplicate of [Javascript - search for a string inside an array of strings](http://stackoverflow.com/questions/5424488/javascript-search-for-a-string-inside-an-array-of-strings) – JJJ Jul 20 '15 at 16:44
  • possible duplicate of [Javascript array search and remove string?](http://stackoverflow.com/questions/9792927/javascript-array-search-and-remove-string) – Jason Cust Jul 20 '15 at 16:45

1 Answers1

1

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;
}
mwilson
  • 12,295
  • 7
  • 55
  • 95