duck duck -3 years ago 82
Javascript Question

Splitting string but leave inner strings intact?

I have a string that looks like this

'a,b,"c,d",e,"f,g,h"'
.

I would like to be able to split this string on
,
but leave encapsulated strings intact getting the following output :
["a","b","c,d","e","f,g,h"]
.

Is there a way to do this without having to parse the string char by char ?

Answer Source

You can create a match of the strings, then map the matches and replace any " in the elements:

let f = 'a,b"c,d",e,"f,g,h"';
let matches = f.match(/\w+|(["]).*?\1/g);

let res = matches.map(e => e.replace(/"/g, ''));
console.log(res);

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download