1

My users copy data from another website that looks like this:

flight-tickets

Which looks like this when pasted:

Houston (IAH) to Cancun (CUN) - Fri, Jul 12
United United 1084 Dep: 6:58PM Arr: 9:15PM 2h 17m Boeing 737 Economy (E)

Cancun (CUN) to Houston (IAH) - Sun, Jul 14
United United 1017 Dep: 2:00PM Arr: 4:23PM 2h 23m Boeing 737 Economy (E)

I am parsing the text that is copied with the below.

var arrayOfLines = document.getElementById("fltInput").value.split('\n');
var arrayOfWords = arrayOfLines[1].split(" ");

I would expect arrayOfWords[1] to be United and arrayOfWords[2] to be 1084, but instead I get 1084 Dep: and 6:58PM Arr::

Here is a JsFiddle. (Slide the slider on the page to see what I mean.)

Clearly the problem is with .split(" ") not seeing the different cells in the copied table as spaces and therefore not splitting the text where I expect.

How can I get around this?

user3666197
  • 1
  • 6
  • 50
  • 92
Wesley Smith
  • 19,401
  • 22
  • 85
  • 133

2 Answers2

1

Its because your strings are not seperated uniformly with single spaces. They may have double or triple spaces in between.

A modified version splitting on 3 spaces:

http://jsfiddle.net/zT38R/6/

var arrayOfLines = document.getElementById("fltInput").value.split('\n');
 console.log(arrayOfLines);
var arrayOfWords = arrayOfLines[1].split("  ");// changed here

Either format your input correctly. Or better use regex based parsing of data.

DhruvPathak
  • 42,059
  • 16
  • 116
  • 175
1

Using the below regex to split on any whitespace solved this for me thanks to this answer

var arrayOfWords = arrayOfLines[1].split(/\s+/g);
Community
  • 1
  • 1
Wesley Smith
  • 19,401
  • 22
  • 85
  • 133