bladeo bladeo - 1 month ago 8
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: https://github.com/xoreos/xoreos-docs/blob/master/specs/bioware/2DA_Format.pdf)

Answer

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 ****';
console.log(str);
var tmp = str.match(/[^\s"']+|"([^"]*)"|'([^']*)'/g);
console.log(tmp);
var n;
tmp.shift();
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);
    if(isNaN(n)){
      //console.log(str + " NaN")
    }
    else tmp[i] = n;
  }

}
console.log(tmp);