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.
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>');
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>');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With