String split method is returning empty string array

Viewed 199

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

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.

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

Related