开发者

How can I split text on commas not within double quotes, while keeping the quotes?

开发者 https://www.devze.com 2023-02-20 15:56 出处:网络
So I\'m trying to split a string in javacript, something that开发者_如何学JAVA looks like this:

So I'm trying to split a string in javacript, something that开发者_如何学JAVA 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


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

0

精彩评论

暂无评论...
验证码 换一张
取 消