bladeo bladeo - 1 year ago 68
Node.js Question

Javascript|node.js regex|function for converting Bioware .2da table row to array

I want to return an array for a table-row string like:

'31 Chicken 2013 "Chi cken" 12.345 ****'

to an array:
["Chicken", 2013, "Chi cken", 12.345, null]

  • The columns in the table are defined by any number of one or more spaces (non-tab) between entries. (Entries which contain spaces are
    enclosed in double quotes and cannot contain quotes themselves.)

  • The first column is always an integer, which can be discarded, so that the array begins with second column.

  • Entry can be an integer, float or string.

  • 4 consecutive asterisks **** denote a null value.

Any help?

(link to fuller format info:

Answer Source

I took some of KRONWALLED's suggestion and a regex from this answer. Couldn't figure out how to get quotes from being added to matched strings.

var str = '31 Chicken    2013 "Chi cken" 12.345 ****';
var tmp = str.match(/[^\s"']+|"([^"]*)"|'([^']*)'/g);
var n;
for (i = 0; i < tmp.length; i++) {
  str = tmp[i];
  if (str === "****") {
    tmp[i] = null;
  else if (str.startsWith('"')) {
    n = str.lastIndexOf('"');
    tmp[i] = str.slice(1,n); 
  else {
    n = Number(str);
      //console.log(str + " NaN")
    else tmp[i] = n;

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download