Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 448
PhilG Avatar asked Mar 14 '18 11:03

PhilG


People also ask

Can I use regex in Includes?

includes does not use regex, see more here: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…

Can I use regex in array?

This is possible when regex applied on this string array. But Build Regular Expression Action only can take String as a Input not a Array of Strings.

How do I check if an array is included?

The includes() method returns true if an array contains a specified value. The includes() method returns false if the value is not found. The includes() method is case sensitive.

What to use instead of includes in JavaScript?

indexOf() The Array#indexOf() function is a common alternative to includes() . The indexOf() function returns the first index in the array at which it found valueToFind , or -1 otherwise.


2 Answers

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.

like image 190
TKoL Avatar answered Sep 24 '22 08:09

TKoL


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;
    }
}
like image 25
MESepehr Avatar answered Sep 24 '22 08:09

MESepehr