简体   繁体   中英

What's the correct way to use an array in a JavaScript RegExp?

I'm trying to use a Regular Expression on an array of strings in JavaScript.

let item1 = "Low-income families";
let item2 = ["Low-income families"];
let item3 = ["Low-income families", "LatinX/Hispanic", "Children and youth", "Rural"];

let key = "Low-income families";

console.log(new RegExp(item1, 'giu').test(key) || key === '') //Prints true
console.log(new RegExp(item2, 'giu').test(key) || key === ''); //Prints true
console.log(new RegExp(item3, 'giu').test(key) || key === ''); //Prints false

My question is, why does item2 return true with that regular expression, but item3 return false ? What would be the correct way to perform the regular expression on the array so that item1 , item2 and item3 all return true ?

item1 and item2.toString() give the same result (a string, with no characters that have special meaning in a regex, that is an exact match for key ).

item3.toString() doesn't give a string that is an exact match for key , nor does it give a substring of it.

You seem to be under the impression that passing an array to the RegExp constructor will create a "match any item in this array" expression, but it does absolutely nothing like that .

You might want to be using item3.includes instead.

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