[英]How can I split text on commas not within double quotes, while keeping the quotes?
So I'm trying to split a string in javacript, something that looks like this: 所以我试图在javacript中拆分一个字符串,如下所示:
"foo","super,foo"
Now, if I use .split(",")
it will turn the string into an array containing [0]"foo" [1]"super [2]foo"
however, I only want to split a comma that is between quotes, and if I use .split('","')
, it will turn into [0]"foo [1]super,foo"
现在,如果我使用
.split(",")
,它将把字符串变成包含[0]"foo" [1]"super [2]foo"
的数组,但是,我只想在引号之间拆分逗号,如果我使用.split('","')
,它将变成[0]"foo [1]super,foo"
Is there a way I can split an element expressing delimiters, but have it keep certain delimiters WITHOUT having to write code to concatenate a value back onto the string? 有没有一种方法可以拆分表示定界符的元素,但是可以保留某些定界符而不必编写代码将值连接回字符串呢?
EDIT: 编辑:
I'm looking to get [0]"foo",[1]"super,foo"
as my result. 我希望得到
[0]"foo",[1]"super,foo"
作为结果。 Essentially, the way I need to edit certain data, I need what is in [0] to never get changed, but the contents of [1] will get changed depending on what it contains. 本质上,我需要编辑某些数据的方式,我需要[0]中的内容永远都不会改变,但是[1]的内容将根据其中包含的内容而改变。 It will get concatenated back to look like
"foo", "I WAS CHANGED"
or it will indeed stay the same if the contents of [1] where not something that required a change 如果[1]的内容不需要更改,它将被连接起来看起来像
"foo", "I WAS CHANGED"
否则它将保持不变。
尝试这个:
'"foo","super,foo"'.replace('","', '"",""').split('","');
For the sake of discussion and benefit of everyone finding this page is search of help, here is a more flexible solution: 为了便于讨论和使所有人受益,发现此页面是在寻求帮助,这是一种更加灵活的解决方案:
var text = '"foo","super,foo"';
console.log(text.match(/"[^"]+"/g));
outputs 输出
['"foo"', '"super,foo"']
This works by passing the 'g' (global) flag to the RegExp instance causing match to return an array of all occurrences of /"[^"]"/
which catches "foo,bar"
, "foo"
, and even "['foo', 'bar']"
( "["foo", "bar"]"
returns [""["", "", "", ""]""]
.) 通过将'g'(全局)标志传递给RegExp实例,从而使match返回所有出现的
/"[^"]"/
数组,该数组捕获"foo,bar"
, "foo"
甚至"['foo', 'bar']"
( "["foo", "bar"]"
返回[""["", "", "", ""]""]
。)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.