2

I am new to Javascript. I want to know why the string split method is returning an array of two empty strings when I use this method with a forwarding slash.

"/".split("/") // => ["", ""]
asked Jul 25, 2021 at 2:42
1

2 Answers 2

4

The string split function considers empty strings as acceptable outputs for splitting. So:

"a".split("a") == ["",""]; // is true, since
"a" == "" + "a" + ""; // is true; and more importantly,
["",""].join("a") == "a"; // is true

In short, the string split function has to give empty strings so that the .join() operator is the inverse of split.

Otherwise, if "/".split("/") gave [], then "/".split("/").join("/") would be "", which violates this inverseness.

If you want to actually get an empty array, you could do "/".split("/").filter(i=>i!=""), or just "/".split("/").filter(i=>i). Or some other variant.

answered Jul 25, 2021 at 2:57
Sign up to request clarification or add additional context in comments.

Comments

1

According to MDN, it will divide the string into ordered sub strings. It will consider space as well.

answered Jul 25, 2021 at 2:48

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.