In English, if a bad situation seems imminent but is finally avoided, we might reply with an interjection like "Thank goodness!" or "Whew!". I know "Thank goodness!" has several possible translations at the beginning of a sentence, but I'm thinking of it being used as a standalone interjection. What is typically said in Spanish in situations like this?
A usual translation for the interjection "Whew!" is
In these situations it is common to say:
It is also common to say
Me salvé por un pelo.
In Uruguay we say also "En el anca de un piojo" but I don't know if this is common elsewhere.
to express how close to the bad situation we had come.
"Thank goodness" might also be "Gracias a Dios", but this may have a religious component.
A common verb is "zafar". For example,
El profesor estaba interrogando alumnos al azar, pero yo zafé por estar en una esquinita, medio oculto.
Just to add to Bruno's answer you can say these aswell:
¡Gracias al cielo!
and for some humor we say sometimes this in Colombia:
Me salvé por un pelo de rana calva.
The translation would be I saved myself by the hair of a bald frog. Since frogs have no hair, a bald frog would have even less hair. So he saved himself by so little!