Evert Pot has pointed out a handy tool that can make escaping strings in and out of your application simpler - Reform.
Reform is a tool that does exactly this. Reform allows you to escape your data for a javascript, xml, html or vbscript (yes it still exists) context. It provides libraries for Java, .NET, PHP, Perl, Python, Javascript and ASP. Pretty cool!
The utility is simply included into the application an called via the static methods it adds. His example shows the escaping of some output text in a Javascript string to correctly prevent it from falling into an evil XSS scheme.