By definition, the i term is a special term known as the imaginary number. It's defined to be
i = sqrt(-1)
where 'sqrt' stands for 'square root'
If we square both sides of the equation above, we get
i = sqrt(-1)
i^2 = (sqrt(-1))^2
i^2 = -1
Notice how squaring the square root has it canceled out. This works because they are inverse operations
So that's why you're able to replace each copy of i^2 with -1