Split JavaScript string with conditions

I can split the string with a comma (,) in JavaScript using split. My line looks like this:

"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"]

+4
source share
2 answers

Assuming there are no unpaired or nested{} , you can use (?![^{}]*})look-ahead to make sure there is no close after the comma }:

\s*,\s*(?![^{}]*})

Watch the regex demo

And a fragment:

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/>");
}
Run codeHide result

\s* used to trim the resulting array entries.

+3
source

The following is a snippet of code:

var arr = "Hojas, DNI, Factura {Con N° de O/C impresa, otra cosa}, Pasaporte, Permiso".split(/\s*,\s*(?![^{}]*})/g);
console.log(arr);
0
source

Source: https://habr.com/ru/post/1611613/


All Articles