2👍
✅
The escapejs
template tag was created for this purpose, you can have a look at the Django documentation for use cases and examples.
Example:
>>> from django.utils.html import escapejs
>>> escapejs('a\nb')
u'a\\u000Ab'
You can, of course, check out the code itself!
Source:stackexchange.com