Split Javascript String With Conditions
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 resul
Solution 1:
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.
Solution 2:
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);
Post a Comment for "Split Javascript String With Conditions"