0

I have a words.txt file that looks something like this:

account
arm
cotton
zoo

Using a XMLHttpRequest I am loading that file, creating an array list containing each line separately using the following code:

var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
  if (this.readyState == 4 && this.status == 200) {
    //this is where I split it
    wordlist = this.responseText.split('\n');
  }
};
xhttp.open('GET', 'words.txt', true);
xhttp.send();

Then I randomly pick one element from the list, let's say account, and split it by '' to get all individual characters:

word = wordlist[randomIndex].split('');

I expect the result to look like this:

["a","c","c","o","u","n","t"]

However, it turns out this way, having an additional empty string at the end:

["a","c","c","o","u","n","t",""]

How do I properly get rid of this?

dasdawidt
  • 13
  • 5
  • You may want to look at [this answer from "Javascript how to split newline"](https://stackoverflow.com/a/45709854/215552)... – Heretic Monkey Oct 30 '19 at 19:29

1 Answers1

2

Windows-style line breaks are not just \n, they're \r\n. Because of this, if your file was created Windows style, splitting at \n will still leave the trailing \r character.

You can simply trim your strings before splitting by character:

word = wordlist[randomIndex].trim().split('');
IceMetalPunk
  • 5,476
  • 3
  • 19
  • 26
  • 1
    you can also `word = new Array.from(wordlist[randomIndex].trim());` – JDunken Oct 30 '19 at 19:13
  • @JDunken True. Works out the same in either case; I just stuck with the OP's choice to use split. – IceMetalPunk Oct 30 '19 at 19:15
  • wasn't a criticism, just showing passers-by an option. – JDunken Oct 30 '19 at 19:16
  • Is there a reason to prefer one of the two methods? – dasdawidt Oct 30 '19 at 19:25
  • @dasdawidt Not that I know of; it's just preference. Array.from doesn't work in Internet Explorer, if you for some reason want to support that. – IceMetalPunk Oct 30 '19 at 19:34
  • You should be careful when using `.split('')` to create an array from a string, especially if you're using anything other than the simple ASCII end of Unicode. See [Unicode string with diacritics split by chars](https://stackoverflow.com/q/10758913/215552) – Heretic Monkey Oct 30 '19 at 19:34
  • @HereticMonkey That same problem happens with Array.from as well :) – IceMetalPunk Oct 30 '19 at 19:42
  • 1
    @IceMetalPunk Sure does. Wasn't really a comment about `Array.from` vs `split('')`. The spread syntax `[...wordlist[randomIndex].trim()]` does better, but still not bullet proof. – Heretic Monkey Oct 30 '19 at 19:49
  • @HereticMonkey Ah, okay. I thought you were responding to dasdawidt's question about which of the two approaches should be preferred :) – IceMetalPunk Oct 30 '19 at 19:54