All occurrences should be replaced when escaping a special character
- INCOMPLETE_STRING_ESCAPE
- Error
- Medium
- No tags
This rule applies when only the first occurrence of a special character is escaped.
When using a string value as HTML or SQL content, special characters like '
, "
, <
, >
and \
often need to be escaped.
The escaping can be accomplished using String.prototype.replace()
. However, some caution is needed because only the first occurrence is replaced in the following cases:
- The search value is specified with a string.
- The search value is specified with a regular expression, but the global flag (
g
) is missing.
If not all occurrences of a special character are escaped properly, the code may become vulnerable to injection attacks.
Noncompliant Code Example
View with compliant examples side by side// Example 1
foo1 = foo1.replace('"', '\\"'); // INCOMPLETE_STRING_ESCAPE alarm because a string search value is used.
// Example 2
foo2 = foo2.replace(/</, '<'); // INCOMPLETE_STRING_ESCAPE alarm because the 'g' flag is missing.
Compliant Code Example
View with noncompliant examples side by side// Example 1
foo1 = foo1.replace(/"/g, '\\"');
// Example 2
foo2 = foo2.replace(/</g, '<');
Version
This rule was introduced in DeepScan 1.32.0.