javascript - 如何在忽略括号中的部分的同时拆分字符串?

标签 javascript

我有一个字符串,我想通过使用逗号作为分隔符将其拆分为一个数组。我不希望括号之间的字符串部分被拆分,即使它们包含逗号也是如此。

例如:

"bibendum, morbi, non, quam (nec, dui, luctus), rutrum, nulla" 

应该变成:

["bibendum", "morbi", "non", "quam (nec, dui, luctus)", "rutrum", "nulla"]

但是当我使用基本的 .split(",") 时,它返回:

["bibendum", " morbi", " non", " quam (nec", " dui", " luctus)", " rutrum", " nulla"]

我需要它返回:

["bibendum", " morbi", " non", " quam (nec, dui, luctus)", " rutrum", " nulla"]

感谢您的帮助。

最佳答案

var regex = /,(?![^(]*\)) /;
var str = "bibendum, morbi, non, quam (nec, dui, luctus), rutrum, nulla"; 

var splitString = str.split(regex);

给你。正则表达式的解释:

,     //Match a comma
(?!   //Negative look-ahead. We want to match a comma NOT followed by...
[^(]* //Any number of characters NOT '(', zero or more times
/)    //Followed by the ')' character
)     //Close the lookahead.

关于javascript - 如何在忽略括号中的部分的同时拆分字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39647555/

相关文章:

javascript - 添加使用向上和向下箭头键选择表格行的功能

javascript - jquery滑动刷新手机网页

javascript - 使用 $.number() 时禁用 keyup/keydown 格式 - Custom D 的 jQuery Number 插件

javascript - react : How to move function outside of component body

javascript - Backbone : Determing if a View has Already Been Loaded

php - 通过按钮更新金额值

javascript - 如何删除jquery sortable中的元素?

javascript - 按时间间隔调用的函数访问全局变量

javascript - karma 覆盖率显示 0/0,100% 覆盖率

javascript - 使用 jQuery 单击背景容器时隐藏元素