Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I split string using `if` condition and separator

I have a variable in javascript with text separated with commas, for example:

var array = "hello,goodbye,test1,test2,1,90m tall"; [NO SPACE AFTER COMMAS]

If I use .split(','); the result is as follows:

array[0] = hello
array[1] = goodbye
array[2] = test1 
array[3] = test2
array[4] = 1
array[5] = 90m tall

But I want this:

array[0] = hello
array[1] = goodbye
array[2] = test1 
array[3] = test2
array[4] = 1,90m tall

How can I do it? I can imagine I have to add some special restriction but I don't know how...I also checked regex but...no success.

like image 913
Cheknov Avatar asked Dec 15 '22 07:12

Cheknov


1 Answers

It depends on what the logic is by which you want to split or not split. If for instance you don't want to split by a comma that has at least two digits following it, then this will do it:

array.split(/,(?!\d\d)/))

This performs a negative look ahead for two digits, and will only match commas which do not have these digits following them.

Snippet:

var array = "hello,goodbye,test1,test2,1,90m tall";

document.body.innerHTML = array.split(/,(?!\d\d)/)
                               .join('<br>');

Follow up question/answer

You asked in comments how to split this:

[hello]blabla,[how,are,you]xx,[i'm fine]

So that a comma would only split if it were followed by an opening bracket.

For this you use positive look ahead (?=):

var array = "[hello]blabla,[how,are,you]xx,[i'm fine]";

document.body.innerHTML = array.split(/,(?=\[)/)
                               .join('<br>');
like image 162
trincot Avatar answered Dec 30 '22 02:12

trincot