PhilG
PhilG

Reputation: 381

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?

Upvotes: 18

Views: 25991

Answers (2)

TKoL
TKoL

Reputation: 13912

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.

Upvotes: 39

MESepehr
MESepehr

Reputation: 778

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;
    }
}

Upvotes: 2

Related Questions