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

  • SEARCH
  • Home
  • 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 6935305
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 27, 20262026-05-27T12:05:05+00:00 2026-05-27T12:05:05+00:00

I have the following type of string var string = "’string, duppi, du’, 23,

  • 0

I have the following type of string

var string = "'string, duppi, du', 23, lala"

I want to split the string into an array on each comma, but only the commas outside the single quotation marks.

I can’t figure out the right regular expression for the split…

string.split(/,/)

will give me

["'string", " duppi", " du'", " 23", " lala"]

but the result should be:

["string, duppi, du", "23", "lala"]

Is there a cross-browser solution?

  • 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-27T12:05:06+00:00Added an answer on May 27, 2026 at 12:05 pm

    Disclaimer

    2014-12-01 Update: The answer below works only for one very specific format of CSV. As correctly pointed out by DG in the comments, this solution does NOT fit the RFC 4180 definition of CSV and it also does NOT fit MS Excel format. This solution simply demonstrates how one can parse one (non-standard) CSV line of input which contains a mix of string types, where the strings may contain escaped quotes and commas.

    A non-standard CSV solution

    As austincheney correctly points out, you really need to parse the string from start to finish if you wish to properly handle quoted strings that may contain escaped characters. Also, the OP does not clearly define what a "CSV string" really is. First we must define what constitutes a valid CSV string and its individual values.

    Given: "CSV String" Definition

    For the purpose of this discussion, a "CSV string" consists of zero or more values, where multiple values are separated by a comma. Each value may consist of:

    1. A double quoted string. (may contain unescaped single quotes.)
    2. A single quoted string. (may contain unescaped double quotes.)
    3. A non-quoted string. (may NOT contain quotes, commas or backslashes.)
    4. An empty value. (An all whitespace value is considered empty.)

    Rules/Notes:

    • Quoted values may contain commas.
    • Quoted values may contain escaped-anything, e.g. 'that\'s cool'.
    • Values containing quotes, commas, or backslashes must be quoted.
    • Values containing leading or trailing whitespace must be quoted.
    • The backslash is removed from all: \' in single quoted values.
    • The backslash is removed from all: \" in double quoted values.
    • Non-quoted strings are trimmed of any leading and trailing spaces.
    • The comma separator may have adjacent whitespace (which is ignored).

    Find:

    A JavaScript function which converts a valid CSV string (as defined above) into an array of string values.

    Solution:

    The regular expressions used by this solution are complex. And (IMHO) all non-trivial regexes should be presented in free-spacing mode with lots of comments and indentation. Unfortunately, JavaScript does not allow free-spacing mode. Thus, the regular expressions implemented by this solution are first presented in native regex syntax (expressed using Python’s handy: r'''...''' raw-multi-line-string syntax).

    First here is a regular expression which validates that a CVS string meets the above requirements:

    Regex to validate a "CSV string":

    re_valid = r"""
    # Validate a CSV string having single, double or un-quoted values.
    ^                                   # Anchor to start of string.
    \s*                                 # Allow whitespace before value.
    (?:                                 # Group for value alternatives.
      '[^'\\]*(?:\\[\S\s][^'\\]*)*'     # Either Single quoted string,
    | "[^"\\]*(?:\\[\S\s][^"\\]*)*"     # or Double quoted string,
    | [^,'"\s\\]*(?:\s+[^,'"\s\\]+)*    # or Non-comma, non-quote stuff.
    )                                   # End group of value alternatives.
    \s*                                 # Allow whitespace after value.
    (?:                                 # Zero or more additional values
      ,                                 # Values separated by a comma.
      \s*                               # Allow whitespace before value.
      (?:                               # Group for value alternatives.
        '[^'\\]*(?:\\[\S\s][^'\\]*)*'   # Either Single quoted string,
      | "[^"\\]*(?:\\[\S\s][^"\\]*)*"   # or Double quoted string,
      | [^,'"\s\\]*(?:\s+[^,'"\s\\]+)*  # or Non-comma, non-quote stuff.
      )                                 # End group of value alternatives.
      \s*                               # Allow whitespace after value.
    )*                                  # Zero or more additional values
    $                                   # Anchor to end of string.
    """
    

    If a string matches the above regex, then that string is a valid CSV string (according to the rules previously stated) and may be parsed using the following regex. The following regex is then used to match one value from the CSV string. It is applied repeatedly until no more matches are found (and all values have been parsed).

    Regex to parse one value from valid CSV string:

    re_value = r"""
    # Match one value in valid CSV string.
    (?!\s*$)                            # Don't match empty last value.
    \s*                                 # Strip whitespace before value.
    (?:                                 # Group for value alternatives.
      '([^'\\]*(?:\\[\S\s][^'\\]*)*)'   # Either $1: Single quoted string,
    | "([^"\\]*(?:\\[\S\s][^"\\]*)*)"   # or $2: Double quoted string,
    | ([^,'"\s\\]*(?:\s+[^,'"\s\\]+)*)  # or $3: Non-comma, non-quote stuff.
    )                                   # End group of value alternatives.
    \s*                                 # Strip whitespace after value.
    (?:,|$)                             # Field ends on comma or EOS.
    """
    

    Note that there is one special case value that this regex does not match – the very last value when that value is empty. This special "empty last value" case is tested for and handled by the js function which follows.

    Example input and output:

    In the following examples, curly braces are used to delimit the {result strings}. (This is to help visualize leading/trailing spaces and zero-length strings.)

        // Return array of string values, or NULL if CSV string not well formed.
        function CSVtoArray(text) {
            var re_valid = /^\s*(?:'[^'\\]*(?:\\[\S\s][^'\\]*)*'|"[^"\\]*(?:\\[\S\s][^"\\]*)*"|[^,'"\s\\]*(?:\s+[^,'"\s\\]+)*)\s*(?:,\s*(?:'[^'\\]*(?:\\[\S\s][^'\\]*)*'|"[^"\\]*(?:\\[\S\s][^"\\]*)*"|[^,'"\s\\]*(?:\s+[^,'"\s\\]+)*)\s*)*$/;
            var re_value = /(?!\s*$)\s*(?:'([^'\\]*(?:\\[\S\s][^'\\]*)*)'|"([^"\\]*(?:\\[\S\s][^"\\]*)*)"|([^,'"\s\\]*(?:\s+[^,'"\s\\]+)*))\s*(?:,|$)/g;
            // Return NULL if input string is not well formed CSV string.
            if (!re_valid.test(text)) return null;
            var a = [];                     // Initialize array to receive values.
            text.replace(re_value, // "Walk" the string using replace with callback.
                function(m0, m1, m2, m3) {
                    // Remove backslash from \' in single quoted values.
                    if      (m1 !== undefined) a.push(m1.replace(/\\'/g, "'"));
                    // Remove backslash from \" in double quoted values.
                    else if (m2 !== undefined) a.push(m2.replace(/\\"/g, '"'));
                    else if (m3 !== undefined) a.push(m3);
                    return ''; // Return empty string.
                });
            // Handle special case of empty last value.
            if (/,\s*$/.test(text)) a.push('');
            return a;
        };
    
        console.log('Test 1: Test string from original question.');
        console.log(CSVtoArray("'string, duppi, du', 23, lala"));
    
        console.log('Test 2: Empty CSV string.');
        console.log(CSVtoArray(""));
    
        console.log('Test 3: CSV string with two empty values.');
        console.log(CSVtoArray(","));
    
        console.log('Test 4: Double quoted CSV string having single quoted values.');
        console.log(CSVtoArray("'one','two with escaped \' single quote', 'three, with, commas'"));
    
        console.log('Test 5: Single quoted CSV string having double quoted values.');
        console.log(CSVtoArray('"one","two with escaped \" double quote", "three, with, commas"'));
    
        console.log('Test 6: CSV string with whitespace in and around empty and non-empty values.');
        console.log(CSVtoArray("   one  ,  'two'  ,  , ' four' ,, 'six ', ' seven ' ,  "));
    
        console.log('Test 7: Not valid');
        console.log(CSVtoArray("one, that's me!, escaped \, comma"));

    Additional notes:

    This solution requires that the CSV string be "valid". For example, unquoted values may not contain backslashes or quotes, e.g. the following CSV string is NOT valid:

    var invalid1 = "one, that's me!, escaped \, comma"
    

    This is not really a limitation because any sub-string may be represented as either a single or double quoted value. Note also that this solution represents only one possible definition for: "Comma Separated Values".

    Edit: 2014-05-19: Added disclaimer.
    Edit: 2014-12-01: Moved disclaimer to top.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have the following array: var idParam = [1,2,3]; I want to send this
I have the following method public static void SerializeToXMLFile(Object obj,Type type, string fileName) {
I have the following case where I want to accept the following routs '/type/view/23'
I have the following command find /var -type f -exec grep param1 {} \;
I have following snippet: static void Main(string[] args) { var container = new UnityContainer();
I have the following method: public MethodInfo FancyGetMethodInfo (object obj, string methodName, Type[] methodSignature)
I have following LINQ statement: string[] str = { a, ab, abcd }; var
When using ASP.net webforms my usual solution would have following type of setup -
I have the following type in wsdl (it is generated by third party tool):
I have the following code: Type type = typeof(T); foreach (PropertyInfo pi in type.GetProperties(BindingFlags.Public

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.