Javascript split by spaces but not those in quotes

后端 未结 3 879
抹茶落季
抹茶落季 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);
    

提交回复
热议问题