0

I'm trying to create a regex which splits a string by : but don't split the quoted parts:

'a:b:c'.split(/*RegExNeeded*/) // => ['a','b','c']
'a:"1:2":d'.split(/*RegExNeeded*/) // => ['a','1:2', 'd']

I've tried ''.split(':') but it is not working, because it'll split the 1:2 as well.

Adam
  • 4,985
  • 2
  • 29
  • 61
  • https://stackoverflow.com/questions/64904/parsings-strings-extracting-words-and-phrases-javascript – epascarello Oct 26 '17 at 14:18
  • You could do it in two steps. One split by one separator, then each of the split elements, split by the second separator – blurfus Oct 26 '17 at 14:18
  • This is basically the same as a CSV parser (albeit a colon in place of a comma). Have you checked out any of the many CSV parsers to see if they support different separators (hint: they do) – Jamiec Oct 26 '17 at 14:24

1 Answers1

4

You could use look ahead to ensure that the number of double quotes that follows a colon is even (not odd):

var res = 'a:"1:2":d'.split(/:(?=[^"]*(?:"[^"]*"[^"]*)*$)/);
console.log(res.join());
trincot
  • 317,000
  • 35
  • 244
  • 286