简体   繁体   中英

RegExp to match a string in JavaScript

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?

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 .

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()) //...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM