2

Currently I am using an autocomplete box within an HTML form.

where "val" contains the contents of the text field:

for (i = 0; i < arr.length; i++) 
{
     if (arr[i].substr(0, val.length).toUpperCase() == val.toUpperCase()) 
     {
     ...code to create drop down list...
     }

}

But this only works with matching patterns from the start. Would like to use RegEx instead to select any array items that contain val anywhere in the array.

I have tried

var results = arr[i].match(/val/i);
if (var)…

But obviously that has failed.

Obviously I could modify the second if statement to loop through the entire length of the array variable, but that would be a waste of time.

Can someone help me with the current usuage?

Daniel Kaplan
  • 701
  • 7
  • 19

2 Answers2

1

You can simply loop through your array with Array.prototype.filter to filter out the unwanted elements. Using the RegExp constructor to dynamically create a regex from a given value.

var regex = new RegExp(val, 'i');

arr.filter(str => str.match(regex))
   .forEach(str => {
     // everything here matches the regex
     // ... code to create drop down list ...
   });

Note that this does allow the user to also type regex in the input box. If you want to take their input literal you'll have to escape the special regex characters.

Alternatively you could also use the String.prototype.includes method if you are searching for a literal match.

var upVal = val.toUpperCase();
arr.filter(str => str.toUpperCase().includes(upVal));

If your arr is a NodeList convert it to an array first using Array.from.

3limin4t0r
  • 19,353
  • 2
  • 31
  • 52
  • I've assigned `new RegExp(val, 'i')` to a variable to avoid re-instantiating the same regex inside the `.filter` loop. eg. `.filter(item => item.match(new RegExp(val, 'i')))` will instantiate a new regex for every item you're trying to match. – 3limin4t0r Mar 25 '19 at 17:01
  • Thanks for this, I believe it is the best way. but within each loop how do I get the full string? Is it part of item? – Daniel Kaplan Mar 27 '19 at 18:29
  • @DanielKaplan `item` is the string, I'll update the answer to better reflect this. – 3limin4t0r Mar 27 '19 at 19:48
1

If you don't care about Internet Explorer (or if you do and use polyfills), there's the String.prototype.includes method. So simply

if arr[i].toUpperCase().includes(val.toUpperCase()) //...
mbojko
  • 13,503
  • 1
  • 16
  • 26