JavaScript split() method resulting in undefined

19,768

Solution 1

Try adding a String cast:

var items = String(rawFile.responseText).split('\n');

Solution 2

After some messing around with this I believe the problem is with your text editor that save the file with line breaks consisting of \r instead of \n, maybe Unix based server?

Anyway, you can replace those and it should work:

var rawText = rawFile.responseText;
rawText = rawText.replace(/\r\n/g, "\n");
rawText = rawText.replace(/\n\r/g, "\n");
rawText = rawText.replace(/\r/g, "\n");
var items = rawText.split('\n');
Share:
19,768
Tiago
Author by

Tiago

Updated on June 21, 2022

Comments

  • Tiago
    Tiago almost 2 years

    I'm working on a simple program that will select a random string from an array.

    I started with a predefined array, but about halfway through wondered if it wouldn't be simpler (or more elegant) to use a text file (.txt), since I have a bit over 1000 items.

    I found this solution here (for which I take no credit) and it is working for me...

    function readTextFile(file) {
        var items = [];
        var rawFile = new XMLHttpRequest();
        rawFile.open("GET", file, true);
        rawFile.onreadystatechange = function() {
            if(rawFile.readyState === 4)
            {
                if(rawFile.status === 200 || rawFile.status === 0)
                {
                    var items = rawFile.responseText.split('\n');
                    alert(items[0]);
                }
            }
        };
        rawFile.send(null);
    }
    
    readTextFile('source.txt');
    

    ...to an extent.

    I want the array items[] to contain one line per item. In other words I want to split per new line. However, all array items are undefiend after items[0] when I use split('\n').

    items[0] in the example above becomes the first sentence, so that much is correct. If I want to alert items[1] I get undefined.

    If I use some other split point, such as split(''), it works correctly, separating each character per item ONLY until the line breaks, after which point I get undefined again.

    Let's say the first line of the .txt is "asd": so 'asd' is defined in array as :

    items[0] = 'a'
    items[1] = 's'
    items[2] = 'd'
    items[3] = undefined
    

    This is what I would get. Where am I wrong?

    Contents of text file:

    asfe
    asdasdasd
    asdasd
    
    fgfg