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

5
  • Is "a,"d,e,f",g" really the string? Commented Aug 12, 2017 at 10:27
  • 1
    What is the source of your string? I think you would need a parser for the general case to handle this. Commented Aug 12, 2017 at 10:28
  • its field from csv file Commented Aug 12, 2017 at 10:32
  • field from csv => 704-wew-9494,"ds daf 787, erwerwe, NC 28134",,,,4/22/2013,5/1/2017,,0 Commented Aug 12, 2017 at 10:36
  • 1
    I would use a csv parser like papaparse or any other parser. Those take care of the various csv formats. Commented Aug 12, 2017 at 10:40

6 Answers 6

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.

Sign up to request clarification or add additional context in comments.

1 Comment

I still dont get why people downvote without saying whats wrong :/
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

3 Comments

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
Nice approach! But isnt the result rather splitted by string / not string ? e.g. "a+'b'"
The speedtest-link seems broken (HTTP status 500). May replace by any alternative.
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

Comments

0

you need to use regexp

var str = 'a,"d,e,f",g';
console.log(str.split(/,"|",/));

6 Comments

This will only work for the special case where ," or ", will be the separater. But based on the comment, the OP is looking for a solution where the quoted column could appear at any place in the row.
when you ask why didn't you tell all cases
my answer is base on you argument
It was not me who wrote the question?
to someone who vote me down, it means my answer is incorrect
|
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.

2 Comments

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
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.
-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?

1 Comment

How should a replace of the " work, if the result should be an array in the form ['a', 'd,e,f', 'g']?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.