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.

InputArgumentsReturnsanyno argumentsstring
Source
BasicSource

Escapes text for embedding inside a quoted JavaScript string.

Given

{"code": `x = "y";` + "\n"}

Template

{{ code | escape_js }}

Result

x = \"y\";\n
ApostropheSource

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 fine
Script 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\u003E
UnicodeSource

Leaves ordinary multi-byte characters untouched inside a string literal.

Given

{"msg": "café"}

Template

{{ msg | escape_js }}

Result

café