Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6714939
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 26, 20262026-05-26T08:33:16+00:00 2026-05-26T08:33:16+00:00

I found this function to parse a csv string into a multi-dim array in

  • 0

I found this function to parse a csv string into a multi-dim array in javascript, here, however I need to update it to also allow single quotes (‘) to be used as the enclosure in addition to double quotes (“) which it already does. i.e. I need it to be able to parse:

CSVToArray('"a, comma","2","3"');
// => [['a, comma', '2', '3']]

As well as this

CSVToArray("'a, comma','2','3'");
// => [['a, comma', '2', '3']]

The function:

// This will parse a delimited string into an array of
// arrays. The default delimiter is the comma, but this
// can be overriden in the second argument.
function CSVToArray( strData, strDelimiter ){
    // Check to see if the delimiter is defined. If not,
    // then default to comma.
    strDelimiter = (strDelimiter || ",");

    // Create a regular expression to parse the CSV values.
    var objPattern = new RegExp(
            (
                    // Delimiters.
                    "(\\" + strDelimiter + "|\\r?\\n|\\r|^)" +

                    // Quoted fields.
                    "(?:\"([^\"]*(?:\"\"[^\"]*)*)\"|" +

                    // Standard fields.
                    "([^\"\\" + strDelimiter + "\\r\\n]*))"
            ),
            "gi"
            );


    // Create an array to hold our data. Give the array
    // a default empty first row.
    var arrData = [[]];

    // Create an array to hold our individual pattern
    // matching groups.
    var arrMatches = null;


    // Keep looping over the regular expression matches
    // until we can no longer find a match.
    while (arrMatches = objPattern.exec( strData )){

            // Get the delimiter that was found.
            var strMatchedDelimiter = arrMatches[ 1 ];

            // Check to see if the given delimiter has a length
            // (is not the start of string) and if it matches
            // field delimiter. If id does not, then we know
            // that this delimiter is a row delimiter.
            if (
                    strMatchedDelimiter.length &&
                    (strMatchedDelimiter != strDelimiter)
                    ){

                    // Since we have reached a new row of data,
                    // add an empty row to our data array.
                    arrData.push( [] );

            }


            // Now that we have our delimiter out of the way,
            // let's check to see which kind of value we
            // captured (quoted or unquoted).
            if (arrMatches[ 2 ]){

                    // We found a quoted value. When we capture
                    // this value, unescape any double quotes.
                    var strMatchedValue = arrMatches[ 2 ].replace(
                            new RegExp( "\"\"", "g" ),
                            "\""
                            );

            } else {

                    // We found a non-quoted value.
                    var strMatchedValue = arrMatches[ 3 ];

            }


            // Now that we have our value string, let's add
            // it to the data array.
            arrData[ arrData.length - 1 ].push( strMatchedValue );
    }

    // Return the parsed data.
    return( arrData );
}
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-26T08:33:16+00:00Added an answer on May 26, 2026 at 8:33 am

    Your base pattern contains some flaws, and not easily extensible: Delimiters are always prefixed by a \\, even when they shouldn’t.

    I’ve rewritten the code, to make it mor ereliable.Multiple quotation types are supported, and delimiters are properly escaped.

    Fiddle: http://jsfiddle.net/qz53J/

    function CSVToArray( strData, strDelimiter ){    
        // Properly escape the delimiter, if existent.
        // If no delimiter is given, use a comma
        strDelimiter = (strDelimiter || ",").replace(/([[^$.|?*+(){}])/g, '\\$1');
    
        //What are the quotation characters? "'
        var quotes = "\"'";
    
        // Create a regular expression to parse the CSV values.
        // match[1] = Contains the delimiter if the RegExp is not at the begin
        // match[2] = quote, if any
        // match[3] = string inside quotes, if match[2] exists
        // match[4] = non-quoted strings
        var objPattern = new RegExp(
                    // Delimiter or marker of new row
            "(?:(" + strDelimiter + ")|[\\n\\r]|^)" +
                    // Quoted fields
            "(?:([" + quotes + "])((?:[^" + quotes + "]+|(?!\\2).|\\2\\2)*)\\2" + 
                    // Standard fields
            "|([^" + quotes + strDelimiter + "\\n\\r]*))"
        , "gi");
    
        // Create a matrix (2d array) to hold data, which will be returned.
        var arrData = [];
    
        // Execute the RegExp until no match is found
        var arrMatches;
        while ( arrMatches = objPattern.exec( strData ) ){
                // If the first group of the RegExp does is empty, no delimiter is
                // matched. This only occurs at the beginning of a new row
                if ( !arrMatches[ 1 ] ){
                        // Add an empty row to our data array.
                        arrData.push( [] );    
                }
    
                var quote = arrMatches[ 2 ]
                if ( quote ){
                        // We found a quoted value. When we capture
                        // this value, unescape any double quotes.
                        var strMatchedValue = arrMatches[ 3 ].replace(
                            new RegExp( quote + quote, "g" ),
                            quote
                        );
                } else {
                        // We found a non-quoted value.
                        var strMatchedValue = arrMatches[ 4 ];
                }
                // Add the found value to the array
                arrData[ arrData.length - 1 ].push( strMatchedValue );
        }
        // Return the parsed data.
        return arrData;
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Yesterday I found this function: function clone(obj) { return typeof obj === 'undefined' ?
I found this from C++FAQ Generally, No. From a member function or friend of
I'm trying to find any reference for this function, but I haven't found anything.
In an app I'm profiling, I found that in some scenarios this function is
Hi I found this function in a utilities code file: Version 1: public static
I found this script which parses a CSV file to XML. Problem is it
I'm writing a function that should parse a string containing a description of a
Found this: Sub SurroundWithAppendTag() DTE.ActiveDocument.Selection.Text = .Append( + DTE.ActiveDocument.Selection.Text + ) End Sub But
found this regex: insert every 10 characters: $text = preg_replace(|(.{10})|u, \${1}. , $text); can
Found this rather strange bug in IE8; element.style.top is limited to 1342177 pixels. Even

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.