1

Just encountered this while posting an answers, and did not figure out why this happens.

Here is the code:

var s = "aaaaaX..";

var a = s.slice(1);
    a = a.slice( 0, a.lastIndexOf("X") );    

var b = s.slice(1).slice( 0, s.lastIndexOf("X") );    

var c = s.slice(1).slice( 0, s.lastIndexOf("X") - 1);

console.log(c);

Why is a not equal to b ? Why does the -1 have to be added so that c == a ?

Demo: http://jsfiddle.net/mb974/

2
  • @cookiemonster Yes, you are right, just figured that out myself but decided not to delete the question as others might encounter the same problem. :) Commented Jun 16, 2014 at 22:48
  • 2
    Because the s in the s.lastIndexOf("X") refers to the unmodified s, not the s.slice(1). The .slice() method doesn't mutate the original. EDIT: ...sorry, my original wording was wrong. Commented Jun 16, 2014 at 22:48

1 Answer 1

2

That's because you have removed one first character from s and assign it to the a variable. So index is lower by 1 than index in string where you didn't remove first character.

Following example will work:

var a = s.slice(1);
    a = a.slice( 0, s.lastIndexOf("X") );    

var b = s.slice(1).slice( 0, s.lastIndexOf("X") ); 

// a == b
Sign up to request clarification or add additional context in comments.

1 Comment

I believe OP wanted aaaa instead of aaaaX, but just a guess.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.