0

i want my string using "," (comma) but my String have some special case please help me

input : a,"d,e,f",g //string in csv`

     var myarray=str.spilt(",");

output: myarray[0] = a ,myarray[1]="d ,myarray[3]=e,myarray[4]=f.....

required output : myarray[0] =a ,myarray[1]="d,e,f",myarray[2] = g

please help me... thanks

Sandip Solanki
  • 704
  • 1
  • 8
  • 15

6 Answers6

1

A small non regex, iterative and slow approach:

var result = [], tmp="", inString = false;
str.split("").forEach(function(char){
  inString = inString != (char === '"');
   if( !inString && char === "," ){
     result.push(tmp);
     tmp = "";
    }else{
     tmp+=char;
    }
});
result.push(tmp);

In action

You may also use a regular for loop instead of the forEach:

for(char of str){ /*...*/ }

However, thats up to you.

Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151
1

This would be a lot smoother with a mapcat operator in JS.

let input = 'a,"d,e,f",g'
var result = []
input.split('"').forEach((e, i) => {
    result = result.concat( i % 2 == 0 ? e.split(',') : e )
})
result = result.filter(e => e != "")

As ChristianFigueroa pointed out: This won't work for cases where the quotes don't surround the whole field: value,val"ue", "value"

However if that is not important for you: jsperf/speedtest

tgebauer
  • 144
  • 1
  • 6
  • This fails in a case where a quote is included in the value, bit isn't the first character. (eg value,val"ue,"value"). There's no rule saying a quote can't appear inside one of the values – ChristianFigueroa Aug 12 '17 at 11:06
  • Nice approach! But isnt the result rather splitted by *string / not string* ? e.g. "a+'b'" – Jonas Wilms Aug 12 '17 at 11:12
  • The speedtest-link seems broken (HTTP status 500). May [replace by any alternative](https://stackoverflow.com/questions/37695890/how-to-profile-javascript-now-that-jsperf-is-down). – hc_dev Feb 17 '22 at 08:34
1

Strongly advise to parse CSV with a tested CSV-parser library instead of any regex.

CSV-parsers for JavaScript

Among the common ones example:

Example usages

Your example using

  • .. Papa Parse, can auto-detect the delimiter and has already a default for quoted-strings: quoteChar: '"' (like yours). Try it online:
var csvInput = 'a,"d,e,f",g';
var results = Papa.parse(csvString);
console.log(results);

Output (copied from console):

{
  data: [
    "a",
    "d,e,f",
    "g"
  ],
  errors: []
  meta: {delimiter: ",", linebreak: "↵", aborted: false, truncated: false, cursor: 11}
}
var input = 'a,"d,e,f",g';
var result = $.csv.toArray(input);
console.log(result);

// even configurable
$.csv.toArrays(input, {
  delimiter: "\"", // already the default, custom value delimiter character
  separator: ',', // already the default, custom field separator character
});

Output:

[
  "a",
  "d,e,f",
  "g"
]

Disadvantage of regular-expressions for CSV parsing

The regex for CSV-parsing can be either simple like split(',') or long, cumbersome and fragile - catasrophic backracking like described on regular-expressions.info: "A Real Example: Matching CSV Records".

Furthermore:

  • a regex is not easy to configure.
  • a regex is hard to document, maintain, modularize or extend.

If you still want to try, read

Related questions

hc_dev
  • 8,389
  • 1
  • 26
  • 38
0

you need to use regexp

var str = 'a,"d,e,f",g';
console.log(str.split(/,"|",/));
raksa
  • 898
  • 6
  • 17
0
myarray = []
while (str) {
    start = str;
    str = str.replace(/(".*?"|[^",]+|)($|,)/, function(match, group1) {
        myarray.push(group1);
        return "";
    });
    if (str == start) break;
}

The code above goes through the CSV string, adding each value it can to the array myarray. If the value has a " as it's first character (may contain commas), it will match until it reaches the next closing ". Otherwise, the regex will just look for the next comma. If it finds something like a value without a closing ", it will automatically stop and myarray will include all the values up to that point that it failed. Empty values (two adjacent commas) will also work.

  • Does not work for longer rows like the example the OP wrote in the comments `704-wew-9494,"ds daf 787, erwerwe, NC 28134",,,,4/22/2013,5/1/2017,,0` – t.niese Aug 12 '17 at 10:53
  • I added a comma in it so now it matches empty values correctly. Other than that it seems to work for me with the given string. – ChristianFigueroa Aug 12 '17 at 10:59
-1

You can clean up the CSV with adding delimiters " to create new columns. This is in excel though but I'm not sure how you parse this data so might not work for you. Or str_replace() them and then str.split?

Muppet
  • 356
  • 1
  • 4
  • 14
  • How should a replace of the `"` work, if the result should be an array in the form `['a', 'd,e,f', 'g']`? – t.niese Aug 12 '17 at 10:42