lllll lllll - 1 year ago 68
Javascript Question

Javascript Parsing Issue

I am trying to parse a text line by line and then parse a line on tokens with

as the delimiter.

So far I have the following:

str = "a\tb\tc\n1\t2\t3\nx\t\y\tz"
console.log( str + "\n");

i = 0;
j = str.indexOf( "\n", i );

sstr = str.substr( i, j );

tokens = sstr.split( '\t' );

console.log( tokens + "\n" );

i = j + 1;
j = str.indexOf( "\n", i ); // (*)

sstr = str.substr( i, j );

console.log( sstr + "\n");

tokens = sstr.split( "\t" );
console.log( tokens + "\n" ); // (**)

Why do I get the following:


instead of the following:


console.log( tokens + "\n" ); // (**)

Did I make a mistake?

Answer Source

You are using j as the end index of the required substring, but the second argument of .substr() is not the end index, it's the number of characters to take. (It works the first time because the start index is 0 so the end index is equal to the number of characters to take.)

Try .slice() instead. (Or substring(), but I prefer .slice() because it is more versatile, and shorter to type.)

sstr = str.slice( i, j );
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download