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("/") // => ["", ""]
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.

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.

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.