Search code examples
javascriptregexparsingquotesdouble-quotes

How can I use regular expressions and javascript to split the following command into tokens:


filter -n ""function(file) { return file.owner == "john"; }""

should be parsed into the following array:

[ 'filter',
  '-n',
  'function(file) { return file.owner == "john"; }' ]

Solution

  • I'm not entirely sure how you want to handle the double quotes. Do you want to also be able to handle strings with only a single double quote on each end, or are the quotes always doubled?

    var string = 'filter -n ""function(file) { return file.owner == "john"; }""';
    var regex  = /([^"\s]+)|""(.*?)""/g;
    var match;
    var result = [];
    
    while (match = regex.exec(string)) {
        result.push(match[1] || match[2]);
    }
    
    alert(result);
    

    Result:

    filter,-n,function(file) { return file.owner == "john"; }