escape_js
Escapes a value for use inside a quoted JavaScript string literal.
It is not safe as bare JavaScript, because escaping leaves a ";", a "(", or an identifier untouched, so a value spliced outside a string literal is still live code. Scalar values are coerced to their string form before escaping.
InputArgumentsReturns
Sourceanyno argumentsstringBasicSource
Escapes text for embedding inside a quoted JavaScript string.
Given
{"code": `x = "y";` + "\n"}Template
{{ code | escape_js }}Result
x = \"y\";\nApostropheSource
Escapes a single quote so the value is safe inside a single-quoted string literal.
Given
{"msg": "it's fine"}Template
{{ msg | escape_js }}Result
it\'s fineScript tagSource
Escapes the angle brackets and slash so the value cannot close a script element.
Given
{"payload": "</script>"}Template
{{ payload | escape_js }}Result
\u003C\/script\u003EUnicodeSource
Leaves ordinary multi-byte characters untouched inside a string literal.
Given
{"msg": "café"}Template
{{ msg | escape_js }}Result
café