4

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

0

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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);

2 Comments

Factura {Con N° de O/C impresa, otra cosa} should be one element, but your code get two
@Grundy: Thanks. Corrected the same.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.