Reputation: 721
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?
Upvotes: 2
Views: 155
Reputation: 14679
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()) //...
Upvotes: 1
Reputation: 21130
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
.
Upvotes: 1