Reputation: 70
I can separate a string by comma (,) in JavaScript with split. My string is as follows:
"Hojas, DNI, Factura {Con N° de O/C impresa, otra cosa}, Pasaporte, Permiso"
The result should be:
["Hojas", "DNI", "Factura {Con N° de O/C impresa, otra cosa}", "Pasaporte", "Permiso"]
I tried to do the following:
"Hojas, DNI, Factura {Con N° de O/C impresa, otra cosa}, Pasaporte, Permiso".split(/,\s+(.+\s{.+})?/g)
But I get the following result: ["Hojas", "DNI, Factura {Con N° de O/C impresa, otra cosa}", "", undefined, "Pasaporte", undefined, "Permiso"]
Upvotes: 4
Views: 698
Reputation: 537
Please find below code snippet:
var arr = "Hojas, DNI, Factura {Con N° de O/C impresa, otra cosa}, Pasaporte, Permiso".split(/\s*,\s*(?![^{}]*})/g);
console.log(arr);
Upvotes: 0
Reputation: 626748
Assuming that there are no unpaired or nested {}
, you can use a (?![^{}]*})
look-ahead to make sure there is no closing }
after the comma:
\s*,\s*(?![^{}]*})
See the regex demo
And a snippet:
var re = /\s*,\s*(?![^{}]*})/g;
var str = 'Hojas, DNI, Factura {Con N° de O/C impresa, otra cosa}, Pasaporte, Permiso';
var res = str.split(re);
for (var i=0; i<res.length; i++) {
document.write(res[i]+ "<br/>");
}
The \s*
are used to trim the resulting array entries.
Upvotes: 3