3

So I have this string:

apple;banana;orange, kiwi;onion,strawberry, avocado

the above string should split into:

   apple
   banana
   orange, kiwi
   onion
   strawberry
   avocado

I found a regex function but it only splits the double quotes " "

   str.split(",(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)");

I tried to replace " " with ; ;

   str.split(",(?=(?:[^\;]*\;[^\;]*\;)*[^\;]*$)");

but it does't work when I replaced with ;

AlexFF1
  • 1,233
  • 4
  • 22
  • 43
  • 1
    are you sure about the wanted result? – Nina Scholz Mar 29 '19 at 13:23
  • 1
    Sounds strange that orange and kiwi aren't splitted. That's a weird split criteria. – briosheje Mar 29 '19 at 13:24
  • @NinaScholz yes I am sure, something similar asked but with double quotes https://stackoverflow.com/questions/18893390/splitting-on-comma-outside-quotes – AlexFF1 Mar 29 '19 at 13:27
  • what is the rule for the last `'onion,strawberry, avocado'` part. why is this part splitted by comma and this `part 'orange, kiwi'` isn't? – Nina Scholz Mar 29 '19 at 13:31
  • @NinaScholz rule for the last 'onion,strawberry, avocado' is that it should split those with commas – AlexFF1 Mar 29 '19 at 13:33
  • 1
    @NinaScholz the comma between `orange` and `kiwi` is between two semicolons and has to be ignored, as per the title. Commas that don't fit this case should split the array. – Nino Filiu Mar 29 '19 at 13:34

2 Answers2

4

You could just split by semicolon or by comma, if semicolon is not following.

var string = 'apple;banana;orange, kiwi;onion,strawberry, avocado',
    array = string.split(/;\s*|,\s*(?!.*;)/);

console.log(array);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
  • nice one strange when I add a semicolon at the end of avocado e.g apple;banana;orange, kiwi;onion,strawberry, avocado; the output is correct but at the end it adds empty string to array, how to ignore the end semicolon? [ "apple", "banana", "orange, kiwi", "onion", "strawberry", "avocado", "" ] – AlexFF1 Mar 29 '19 at 13:47
  • 1
    in this case th splitting works as intended, you could add a filter for removing empty strings, like `.filter(Boolean)` – Nina Scholz Mar 29 '19 at 13:51
  • so following @NinaScholz answer if you looking to ignore semicolon at the end string.split(/;\s*|,\s*(?!.*;)/).filter(Boolean) thanks for answer NinaScholz – AlexFF1 Mar 29 '19 at 13:57
2

const str = 'apple;banana;orange, kiwi;onion,strawberry, avocado';

console.log(
  str
  
    // split at each semicolon
    .split(';')
    
    // split at each comma, only for the first and last elements
    .map((x,i,arr) => (i==0 || i==arr.length-1) ? x.split(',') : [x])
    
    // merge the arrays
    .reduce((acc, cur) => [...acc, ...cur], [])

    // trim for clean result
    .map(x => x.trim())
    
)
Nino Filiu
  • 16,660
  • 11
  • 54
  • 84