admin管理员组文章数量:1426483
So I'm trying to split a string in javacript, something that looks like this:
"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 ma that is between quotes, and if I use .split('","')
, it will turn into [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. 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. 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
So I'm trying to split a string in javacript, something that looks like this:
"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 ma that is between quotes, and if I use .split('","')
, it will turn into [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. 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. 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
-
What's the final result you want from
"foo","super,foo"
? – Student Commented Mar 30, 2011 at 17:40 - Yes, thanks for the reminder to add it, Tom – James Commented Mar 30, 2011 at 17:43
- sorry, you want the output the same as the input? – Student Commented Mar 30, 2011 at 17:44
2 Answers
Reset to default 5Try this:
'"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 [""["", "", "", ""]""]
.)
本文标签:
版权声明:本文标题:javascript - How can I split text on commas not within double quotes, while keeping the quotes? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745388286a2656477.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论