How to create sub string in a line read from text file separated by comma

1.1k views Asked by At

I am java script newbie and i have a text file like this Address.txt :

Andhra Pradesh,East Godavari,Reach within 36 Hrs
Andhra Pradesh,Guntur,Reach within 36 Hrs
Andhra Pradesh,Krishna,Reach within 36 Hrs
Andhra Pradesh,Visakhapatnam,Reach within 36 Hrs
Andhra Pradesh,Chittoor,Reach within 36 Hrs

Now i want to separate each loine by substring by comma , hence there will be 3 sub strings. Which must be stored in three arrays.

How to do that in Javascript lets say my way reading this file is :

 $.ajax({
            type: 'GET',
            url: 'Address.txt',
            dataType: 'text',
        }).success(function (test)
        {
              alert('inside ajax : '+test);//lets say this show aall the data of test file
            var col1 = [];
            var col2 = [];
           var col3 = [];
            var j = 0;
                //How to concert them in substring and save in these tree columns ?
            for (var i = 0; i <= test.length - 3; i = i + 3) 
            {

            }     

        })
3

There are 3 answers

0
cbreezier On BEST ANSWER

Use str.split()

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split

So first we need to split on the newline \n character to get all of the lines. Then for each line, we split on the comma , character to get each of the three substrings, as you say.

Here is a verbose but simple way to do it:

var lines = test.split('\n');
for (var i = 0; i < lines.length; i++) {
    var cols = lines[i].split(',');
    col1.push(cols[0]);
    col2.push(cols[1]);
    col3.push(cols[2]);
}

So for every line, we add the first substring to the col1 array, the second to the col2 array, etc.

0
Nikhil Batra On

You should use:

var array = string.split(',');

split function will split the string based on the comma and you will get the array in the var array.

Use the above logic for each of the three strings you have mentioned and store it in the cols as you wish.

0
Deepak gupta On

Check out this google script to convert any CSV file into array or objects

http://jquery-csv.googlecode.com/git/examples/basic-usage.html