I don’t know why my regular expression captures several empty elements

I have this regular expression: ([az]+)(?:\.) .

Using this in Javascript: "test.thing.other".split(/([az]+)(?:\.)/); ends up giving me an array like this:
["", "test", "", "thing", "other"] .
I do not know why the first and third elements are placed in this array. Can someone show me what I'm doing wrong?

+4
source share
2 answers

Depending on your question and the comment ā€œCapturing az before a certain period of timeā€ I believe that you should use String.match sooner, for example:

 arr = "test.thing.other".match(/[az]+(?=\.)/g); 

gives:

 ["test", "thing"] 
+3
source

Brackets are the reason. Heres what MDN says string.split :

If separator is a regular expression containing brackets for parentheses, then each time the separator is matched, the results (including any undefined results) of the brackets for writing are combined into an output array.

They also warn:

However, not all browsers support this feature.

Thus, this result may be inconsistent. If you just want to separate the contents of the content, remove the parentheses:

 >> 'test.thing.other'.split(/[az]+\./) ["", "", "other"] 

Which may also not be what you want, but it is the expected result that has received your expression.

If you want to divide by dots, you need to specify this exactly in the regular expression: dot.

 >> 'test.thing.other'.split(/\./) ["test", "thing", "other"] 
+2
source

All Articles