0

Input var str='john,doe,"1,234.56",0.00,true'

I tried using following regex

var arr = str.match(/(".*?"|[^",\s]+)(?=\s*,|\s*$)/g);

but getting error of unterminated string .

A non-regex solution to achieve the following output

Desired output :

john,doe,1,234.56,0.00,true

var str='john,doe,"1,234.56",0.00,true'
var arr = str.match(/(".*?"|[^",\s]+)(?=\s*,|\s*$)/g);
console.log(arr.join("."))
mplungjan
  • 169,008
  • 28
  • 173
  • 236
  • desired output does not match the subject. – AZ_ Jun 03 '20 at 17:55
  • I would solve that with two level regex, first extract all strings that are in an double quotes and than split them depending on commas (by ignoring those that were in double quotes) – Sheki Jun 03 '20 at 17:57
  • please share how – Normie Coder Jun 03 '20 at 17:58
  • @mplungjan I think that's the problem. He's using that solution but it isn't working as he expects – user120242 Jun 03 '20 at 18:08
  • @user120242 as you can see in the snippet I just made, it works fine – mplungjan Jun 03 '20 at 18:10
  • @mplungjan he wants it to strip the quotes for him. although honestly don't know why he doesn't just trim them off. oh, he's asking about unterminated string. must be a salesforce thing with quotes – user120242 Jun 03 '20 at 18:10
  • Where does it say that? That is not possible. "1,234.56" is a string – mplungjan Jun 03 '20 at 18:13
  • @mplungjan I'm not the OP, but the OP's desired output does not include the quotes around ,1,234.56,0.00, so he wants "1,234.56,0.00" not "\"1,234.56,0.00\"". None of those examples strip the quotes for you. Need another dupe link for stripping quotes. – user120242 Jun 03 '20 at 18:21
  • The escaped quotes are the console log - to strip quotes do a join and a simple replace but then you have a string again with commas – mplungjan Jun 03 '20 at 18:26
  • @mplungjan you mean .map and trim or slice right? right now it gives `"\"1234\""` not `"1234"` because the regex matches on `".*?"`. what he wants is `(?<").*?(?=")` to exclude quotes, or `"(.*?)"` and extracting the third match group (must use matchAll). or `.map(x=>x[0]==='"'&&x[x.length-1]==='"'?x.slice(1,-1):x)`. the last solution being trivial enough that he should have been able to find a (separate) dupe for it without much issue – user120242 Jun 03 '20 at 18:43
  • 1
    @mplungjan `'john,doe,"1,234.56",0.00,true'.match(/(".*?"|[^",\s]+)(?=\s*,|\s*$)/g)[2] !== "1,234.56"` but `'john,doe,"1,234.56",0.00,true'.match(/(".*?"|[^",\s]+)(?=\s*,|\s*$)/g)[2] === '"\"1,234.56\""` – user120242 Jun 03 '20 at 19:14

1 Answers1

0

you can use negative looakahead and negative lookbehind

var str='john,doe,"1,234.56",0.00,true';
var out = str.match(/(?<!\")([\w\.]+)(?!")(?:,|$)/g)
console.log(out)
AZ_
  • 3,094
  • 1
  • 9
  • 19