Using string concatenation to construct JavaScript code can be error-prone, or in the worst case enable code-injection if an input is constructed by an attacker.

If using JSON.stringify or a HTML sanitizer to sanitize a string inserted into JavaScript code, then make sure to perform additional sanitization or remove potentially dangerous characters.

The below example constructs a function that assigns the number 42 to the property key on an object obj. However, if key contains </script>, then the generated code will break out of a <script> if the generated code is inserted into a <script> tag.

The issue has been fixed in the below by escaping potentially dangerous characters.

  • OWASP: Code Injection.