Jojo Coana Jojo Coana - 2 months ago 9
Javascript Question

javascript for loop - how to get text before [i]

I'm trying to create a parser to parse my coordinate data into json. The data is in a text file in a simple x,y format. I'm trying to get the the text before [i], is that possible with .split()?

Code:

function visualize()
{
if(currDoc == null)
{
var location = window.prompt("Please enter the name of the dataset file, and make sure it is in the data directory. Current supported formats txt.");
location = "data/" + location;
jQuery.get(location, function(data) {
data = data.replace(/\s/g, '');
var length = data.length;
var commaCount = 0;
for(var i=0;i<length;i++)
{
if(data[i] == ",")
{
commaCount += 1;
if(commaCount == 2)
{
//get text before [i]
}
}
}
}, "text").fail(function(){ alert("File not found. Did you enter the file name correctly?") });
}
else
{
alert("A dataset is already visualized");
}
}

Answer

If your data is delimited by commas like this x1,y1,x2,y2,...,xn,yn you can use the split function to split the string into tokens. Then you can iterate through them to collect whatever you need from the input.

For example if you need x and y pairs you would do something like this:

function visualize()
{
    if(currDoc == null)
    {
        var location = window.prompt("Please enter the name of the dataset file, and make sure it is in the data directory. Current supported formats txt.");
        location = "data/" + location;
        jQuery.get(location, function(data) {
            data = data.replace(/\s/g, '');

            // split the string 'x1,y1,...,xn,yn' into tokens ['x1', 'y1', ... 'xn', 'yn']
            var tokens = data.split(',');

            // iterate over all tokens using a step of 2 (i += 2)
            // Note: if you have an odd number of tokens the last one will be ignored
            // (this is by design because you are expecting x,y pairs)
            for(var i = 1; i < tokens.length; i += 2)
            {
                // print the (x,y) pair to the console
                console.log("New pair (" + tokens[i-1] + "," + tokens[i] + ")");
            }
        }, "text").fail(function(){ alert("File not found. Did you enter the file name correctly?") });
    }
    else
    {
        alert("A dataset is already visualized");
    }
}