Cross-site-scripting attacks are a real worry for any major website and protecting aginst them is not an easy task. Malicious code must be filtered out when the user submits any text. The most basic attacks are easy to prevent e.g. attempting to submit:
This can be prevented simply by escaping the HTML tags or recognising the script tag and removing or disallowing it. More complex attacks may use different character encodings to fool filters or place scripts inside tags users are allowed to use. In the Twitter case, it seems the exploit focused on the way in which it handled internal URLs. Some relatively simple filtering could have seemingly prevented this issue ever arising.