HypeWolf
HypeWolf

Reputation: 850

How to split a string in Javascript, but not if it's between quotes?

I found a lot of questions about simple splits, but my file is similar to a csv file and some strings are between quotes and may contain commas.

Sample:

myKey,this is a string,"This is yet, another, string"

Desired output:

["myKey", "this is a string", "This is yet, another, string"]

I found a similar question but I was unable to adapt it properly:

str.split(/([^,"]+|[^,"]*)+/g)[0]

It gives me the first character of the string instead. I also tried adding ?: after the first parenthesis like I saw, but it didn't seem to matter.

Upvotes: 1

Views: 1316

Answers (2)

Thomas Brierley
Thomas Brierley

Reputation: 1217

'myKey,this is a string,"This is yet, another, string"'
    .split(/,(?=(?:[^"]*"[^"]*")*$)/g);
// ["myKey", "this is a string", "\"This is yet, another, string\""]

This works by making sure there are zero or more pairs of quote chars ahead of the comma until the end of the string. If there are an odd number of quotes ahead the comma it will not be matched since it should be within a quote provided all quotes are closed in the string.

Upvotes: 1

trincot
trincot

Reputation: 351084

If there are no special cases with escaped quotes within quotes, and the input is valid, then you could use this:

var s = 'myKey,this is a string,"This is yet, another, string"';
var result = Array.from(s.matchAll(/[^",]+|"([^"]*)"/g), ([a,b]) => b || a);
console.log(result);

Upvotes: 1

Related Questions