1

I open url http://localhost where I load my js script.

Inside my js script I execute:

'use strict';

    var path = window.location.pathname;

    console.log(path); // it prints /

    var arr = path.split('/');

    if (arr.length === 0) { //actual length is 2
        console.log('test'); //not executed
    }

So test is not printed and my arr contains two elements and they are empty. Why does length of the array equal 2?

2
  • 4
    You'll get two parts, everything before and after the /. Since your input is /, youll end up with two empty strings. split is not a strip function. Commented Feb 1, 2018 at 14:41
  • “and my arr contains two elements and they are empty. Why?” - because there wasn’t anything to the left or the right of the / to begin with, so if you split that at the slash, you are left with two “empty halves” ... Commented Feb 1, 2018 at 14:41

1 Answer 1

2

You are located in / (root of the server). If you use / as a separator in your split, you will have n+1 elements, n being the number of separators in your string.

In other words, you end up with path being equal to [THING 1]/[THING 2] (both things being empty strings) which gives you an arr containing ['', ''].

Your arr has length 2, both elements being empty strings.

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

1 Comment

Thanks! I've been thinking it has to return empty array like in some other languages :(

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.