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

Share Improve this question edited Feb 19, 2012 at 19:32 outis 77.5k23 gold badges154 silver badges226 bronze badges asked Mar 30, 2011 at 17:36 JamesJames 5,6529 gold badges35 silver badges43 bronze badges 3
  • 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
Add a ment  | 

2 Answers 2

Reset to default 5

Try 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 [""["", "", "", ""]""].)

本文标签: