The code below is responsible to iterate the eachFilter array and then process the values in the array.


var eachFilter = ['stk_product In List 1002,1004','stk_status In List W,N'];

for(var i = 0; i < eachFilter.length ; i++){

     var stk = ['stk_product','stk_status'];
     var len1=0, len2=0, len3=0; 

     var re1 = new RegExp('\\b' + stk[i] + '\\b');

     //First Match
     var index1 = eachFilter[i].match(re1); 
     len1 = index1[i].length+2;

     //Second Match
     var re2 = new RegExp('\\b' + 'In List' + '\\b');

     var index2 = eachFilter[i].match(re2);
     len2 = index2[i].length+2;

     //Third Match                                                                  
     len3 = (len1 + len2)-1;


Output 1:

"In List"

Output 2:

TypeError: index1[i] is undefined

Output 1 is correct but when it comes to Output 2 an error is shown. Did I miss or did something wrong?

Your help is kindly appreciated.

Thank You.

Edited by solomon_13000

4 Years
Discussion Span
Last Post by Taywin

The problem is in line 15 var index1 = eachFilter[i].match(re1);. Do you understand how match() function works? Have you ever tried to print out what value returned by match() function?

If you do not have grouping in your regex, the function (in JavaScript) will return an array size of 1 if it could match, or null value if it couldn't.

var index1 = eachFilter[i].match(re1);
// this will return [MATCHED_VALUE] to your index1 (in your case)
// but you are using 'i' as index which in the second loop is now 1
// the index1 length is 1, so it has only '0' index and no '1' index

To fix this is to use [0] instead of [i]. However, this will break your script again if there is no match.

By the way, what you are trying to do here? You are not utilizing regex but rather hard-coded it. If you are going to do the way you are doing, using string split() function would be easier.

Edited by Taywin

This article has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.