使用条件拆分JavaScript字符串 [英] Split JavaScript string with conditions
本文介绍了使用条件拆分JavaScript字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我可以用JavaScript中的逗号(,)分隔字符串。我的字符串如下:
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"
结果应该是:
["Hojas", "DNI", "Factura {Con N° de O/C impresa, otra cosa}", "Pasaporte", "Permiso"]
我尝试执行以下操作:
"Hojas, DNI, Factura {Con N° de O/C impresa, otra cosa}, Pasaporte, Permiso".split(/,\s+(.+\s{.+})?/g)
但我得到以下结果: [Hojas, DNI,Factura {Con N°de O / C impresa,otra cosa},,undefined,Pasaporte,undefined,Permiso]
推荐答案
假设没有未配对或嵌套的 {}
,您可以使用a (?![^ {}] *})
预测以确保没有关闭}
之后逗号:
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*(?![^{}]*})
参见正则表达式演示
和一个片段:
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/>");
}
\s *
用于修剪结果数组条目。
The \s*
are used to trim the resulting array entries.
这篇关于使用条件拆分JavaScript字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文