Better encoding of javascript

Fixes #2988
This incorporates more rigorous encoding of JS strings for the sake of robustness.
Missing test cases for these functions are now included.