Javascript split by spaces but not those in quotes

后端 未结 3 864
抹茶落季
抹茶落季 2020-12-03 15:56

The goal is to split a string at the spaces but not split the text data that is in quotes or separate that from the adjacent text.

The input is effectively a string

相关标签:
3条回答
  • 2020-12-03 16:14

    Any special reason it has to be a regexp?

    var str = 'a:0 b:1 moo:"foo bar" c:2';
    
    var parts = [];
    var currentPart = "";
    var isInQuotes= false;
    
    for (var i = 0; i < str.length, i++) {
      var char = str.charAt(i);
      if (char === " " && !isInQuotes) {
        parts.push(currentPart);
        currentPart = "";
      } else {
        currentPart += char;
      }
      if (char === '"') {
        isInQuotes = !isInQuotes;
      }
    }
    
    if (currentPart) parts.push(currentPart);
    
    0 讨论(0)
  • 2020-12-03 16:29

    You could approach it slightly differently and use a Regular Expression to split where spaces are followed by word characters and a colon (rather than a space that's not in a quoted part):

    var str = 'a:0 b:1 moo:"foo bar" c:2',
        arr = str.split(/ +(?=[\w]+\:)/g);
    /* [a:0, b:1, moo:"foo bar", c:2] */
    

    Demo jsFiddle

    What's this Regex doing?
    It looks for a literal match on the space character, then uses a Positive Lookahead to assert that the next part can be matched:
    [\w]+ = match any word character [a-zA-Z0-9_] between one and unlimited times.
    \: = match the : character once (backslash escaped).
    g = global modifier - don't return on first match.

    Demo Regex101 (with explanation)

    0 讨论(0)
  • 2020-12-03 16:30

    You can use this regex for split:

    var s = 'a:0 b:1 moo:"foo bar" c:2';
    
    var m = s.split(/ +(?=(?:(?:[^"]*"){2})*[^"]*$)/g);
    //=> [a:0, b:1, moo:"foo bar", c:2]
    

    RegEx Demo

    It splits on spaces only if it is outside quotes by using a positive lookahead that makes sure there are even number of quotes after a space.

    0 讨论(0)
提交回复
热议问题