Before asking whether the pregnancy was planned, you might examine what's driving your curiosity and how the answer may affect your relationship.
If planned, would you feel betrayed that you didn't know beforehand? Does it make you question the strength/intimacy of your friendship that they didn't tell you as soon as they decided to have a child? Do you feel you should've been consulted?
If unplanned, would you accept and support their decision to continue the pregnancy? Will you feel the need to inform them of your opinion (praising or criticising)? Do you think your opinion of them and their relationship will be affected?
Does the thought of your friends becoming parents scare you? Are you dreading their changing priorities?
Are you genuinely happy and want to be supportive, or are you looking for an opportunity to express your unsolicited opinion on the matter?
There are almost certainly other drivers, but I can't think of a reason to ask if a pregnancy is planned that doesn't come from a place of judgment.
Even to people whose health is threatened by pregnancy, asking if it was planned implies carelessness toward birth control, personal health, and/or the child's future: Why would you risk dying? / How could you be so stupid?
Now, if you cannot suppress this burning need to know...
Congratulations! I am so happy for you! I had no idea you were planning on having a baby - this is wonderful news!
...is the least offensive way I can think of to bring it up. This way, your curiosity is I directly expressed, and they can choose whether to answer a potentially intrusive question. Regardless of the answer, I wouldn't press the issue.