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

Code:

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');
     console.log(eachFilter[i].match(re1));

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

     //Second Match
     var re2 = new RegExp('\\b' + 'In List' + '\\b');
     console.log(eachFilter[i].match(re2));

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

     //Third Match                                                                  
     len3 = (len1 + len2)-1;
     console.log(eachFilter[i].substring(len3,(eachFilter[i].length)-1));

}

Output 1:

"stk_product"
"In List"
1004,1006

Output 2:

"stk_status"
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.

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.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.