James
James

Reputation: 5642

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:

"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"

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

Upvotes: 1

Views: 3201

Answers (2)

jvatic
jvatic

Reputation: 4036

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

Upvotes: 2

Chandu
Chandu

Reputation: 82903

Try this:

'"foo","super,foo"'.replace('","', '"",""').split('","');

Upvotes: 5

Related Questions