Take the following example:
var name = '<%= request['name'] %>';
In that simple example, normal HTML encoding won't work because you've got apostrophes. But if you're inside double quotes, you have to deal with those, and apostrophes might be perfectly legitimate characters. To deal with that easily, just replace it with something like this:
var name = document.forms['holder'].elements['uname'].value;
<input type="hidden" name="uname" value="<%= encode(request['name']) %>"/>
This way, you don't have to think about what kind of quotes you're in (if any), you just let your framework's trusty encoding library do the heavy lifting for you.