Trying to exclude the {} from a string such as below with regex, but so far the {} is still in the created array. Please see jsfiddle example (example part of larger code so I understand the code can be simplified). Resultat is:
["{1", "\"FAAS\"}"]
But would like
["1", "\"FAAS\""]
https://jsfiddle.net/173os8w6/
var objectX = {};
var text = `{1 "FAAS"}`;
var lines = text.split('\n');
for (var line = 0; line < lines.length; line++) {
const regex = /{([^\s"]+)|"([^"]*)"}/g;
var row2 = [];
let result = "";
while(result = regex.exec(lines[line])) {
row2.push(result[0]); //push parts to array
}
console.log(row2);
}
You need to analyze the captures and add the right values accordingly:
while(result = regex.exec(lines[line])) {
if (result[1]) {
row2.push(result[1]);
} else {
row2.push(result[2]);
}
}
Here is your fixed JavaScript demo:
var objectX = {};
var text = `{1 "FAAS"}`;
var lines = text.split('\n');
for (var line = 0; line < lines.length; line++) {
const regex = /{([^\s"]+)|"([^"]*)"}/g;
var row2 = [];
let result = "";
while (result = regex.exec(lines[line])) {
if (result[1]) {
row2.push(result[1]);
} else {
row2.push(result[2]);
}
}
console.log(row2);
}