We're a community of 1076K IT Pros here for help, advice, solutions, professional growth and fun. Join us!
1,075,707 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Start New Discussion Reply to this Discussion

Regular Expression and Index Issue

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.

2
Contributors
1
Reply
4 Hours
Discussion Span
4 Months Ago
Last Updated
3
Views
solomon_13000
Junior Poster
114 posts since Jul 2009
Reputation Points: 24
Solved Threads: 0
Skill Endorsements: 0

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.

Taywin
Posting Maven
2,633 posts since Apr 2010
Reputation Points: 275
Solved Threads: 375
Skill Endorsements: 17

This article has been dead for over three months: Start a new discussion instead

Post: Markdown Syntax: Formatting Help
 
You
 
© 2013 DaniWeb® LLC
Page rendered in 0.3115 seconds using 2.65MB