用逗号分割一个字符串,但使用 Javascript 忽略双引号内的逗号 [英] Split a string by commas but ignore commas within double-quotes using Javascript
本文介绍了用逗号分割一个字符串,但使用 Javascript 忽略双引号内的逗号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在寻找 [a, b, c, "d, e, f", g, h]
变成 6 个元素的数组:a, b, c, "d,e,f", g, h.我正在尝试通过 Javascript 来做到这一点.这是我目前所拥有的:
I'm looking for [a, b, c, "d, e, f", g, h]
to turn into an array of 6 elements: a, b, c, "d,e,f", g, h. I'm trying to do this through Javascript. This is what I have so far:
str = str.split(/,+|"[^"]+"/g);
但现在它正在拆分双引号中的所有内容,这是不正确的.
But right now it's splitting out everything that's in the double-quotes, which is incorrect.
好的,对不起,我对这个问题的措辞非常糟糕.我得到的是一个字符串而不是一个数组.
Okay sorry I worded this question really poorly. I'm being given a string not an array.
var str = 'a, b, c, "d, e, f", g, h';
我想使用类似split"函数的东西将那个变成一个数组.
And I want to turn that into an array using something like the "split" function.
推荐答案
这就是我要做的.
var str = 'a, b, c, "d, e, f", g, h';
var arr = str.match(/(".*?"|[^",s]+)(?=s*,|s*$)/g);
/* 将匹配:
(
".*?" double quotes + anything but double quotes + double quotes
| OR
[^",s]+ 1 or more characters excl. double quotes, comma or spaces of any kind
)
(?= FOLLOWED BY
s*, 0 or more empty spaces and a comma
| OR
s*$ 0 or more empty spaces and nothing else (end of string)
)
*/
arr = arr || [];
// this will prevent JS from throwing an error in
// the below loop when there are no matches
for (var i = 0; i < arr.length; i++) console.log('arr['+i+'] =',arr[i]);
这篇关于用逗号分割一个字符串,但使用 Javascript 忽略双引号内的逗号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文