It seems like this is a solved problem in older frameworks (Django, Rails), but I can't for the life of me find a solution in Express.
A super common pattern in one-page webapps is to use template data to create html and then echo the same data as JSON to the client so that it can maintain state.
each comment as comments
div= comment
script.
var comments = !{JSON.stringify(comments)}
Obviously this isn't safe because a user could easily create a comment that closes the script tag and performs all kinds of nastiness. What's the proper way to deal with this then?
I've seen people claim you can get by with just
JSON.stringify(comments).replace(/<\//g, '<\/')
but that seems naive especially when working with large, forgetful teams.
Similarly, I wrote a function that html escapes recursively before stringifying, but replacing "
with "
in every string seems like overkill and bad for data binding.
EDIT
For reference, here's Django's solution https://docs.djangoproject.com/en/dev/ref/templates/builtins/#escapejs