3

I get the following output when I use split with regex on a string.

string = "12345678"

string.split(/(..)/)

=> ["", "12", "", "34", "", "56", "", "78"]

Why am I getting empty strings from the split method? I realize that using the scan method would give me pairs without the empty strings, but I want to know why split is giving me empty strings.

5
  • 3
    @WiktorStribiżew It is not a duplicate. Read the question. Commented Feb 16, 2016 at 17:58
  • 3
    @WiktorStribiżew - The linked question solves how to get the result I wanted. I wanted to know why it was giving me empty strings. Commented Feb 16, 2016 at 18:02
  • Ok, I see it is difficult to find another original question. Let's keep this one. Commented Feb 16, 2016 at 18:08
  • So, now it is OK to ask two questions: "how can I solve it" and "why does my code fail"? It just feels illogical, I would "merge" both into one. If you know any meta post that discusses it, please share. Commented Feb 16, 2016 at 18:43
  • @WiktorStribiżew - I see what you mean. I will edit my question to be more focused. Commented Feb 16, 2016 at 18:55

1 Answer 1

4

As for the initial empty string, it is because the original purpose of split is to delimit a string into fields with a delimiter. It always assumes that there is a field before a delimiter, even if it is empty. As for the other empty strings, it is because the delimiters are adjacent.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.