简体   繁体   中英

array.includes returns false using regex

I have this array:

array = ['S2B_MSIL1C_20180310T041559_N0206_R090_T46QEK_20180310T075716.SAFE'];

and this regex:

regex = new RegExp('S2B_MSIL1C_20180310T041559_N0206_R090_T46QEK_20180310T075716' + '.SAFE','g');

When I use array.includes(regex); , false is returned. Have I missed something?

Use Array.some

var yourRegex = /pattern/g ;
var atLeastOneMatches = array.some(e => yourRegex.test(e));

Array.some returns true after the first one in the array returns true. If it goes through the whole array with no true , it returns false.

RgExps are not for searching on Arrays, and includes method is for finding if your required object is included on the array or not. and here you passed and Regex object to your include method so it tells you that there is no regex object included your array.

you have to do one of the belows:

array.includes('S2B_MSIL1C_20180310T041559_N0206_R090_T46QEK_20180310T075716' + '.SAFE');

or

var yourRegex = /pattern/g ;
for(var i = 0 ; i<arr.length ; i++)
{
    if(yourRegex.test(arr[i]))
    {
        //Founded
        return true;
    }
}

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