Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Splitting a comma-separated string but ignoring commas between semicolons using JavaScript

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 ;

like image 333
AlexFF1 Avatar asked Oct 26 '25 08:10

AlexFF1


1 Answers

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);
like image 128
Nina Scholz Avatar answered Oct 28 '25 20:10

Nina Scholz