Files
codeql/javascript/ql/src/StandardLibrary/ParseIntRadix.qhelp
2018-08-02 17:53:23 +01:00

52 lines
1.4 KiB
XML

<!DOCTYPE qhelp PUBLIC
"-//Semmle//qhelp//EN"
"qhelp.dtd">
<qhelp>
<overview>
<p>
On some platforms, the builtin function <code>parseInt</code> parses strings starting with the digit
<code>0</code> as octal values (unless an explicit radix is provided). This can lead to unexpected
results when parsing decimal numbers that may be zero-padded, such as dates.
</p>
</overview>
<recommendation>
<p>
Provide an explicit radix as the second parameter to <code>parseInt</code>.
</p>
</recommendation>
<example>
<p>
In the following example, <code>parseInt</code> is used to convert the contents of a field in an HTML
form to a number:
</p>
<sample src="examples/ParseIntRadix.js" />
<p>
Now assume that a user has entered a zero-padded decimal number, say <code>09</code>, into the form.
Since the first digit is a zero, older versions of <code>parseInt</code> interpret this value as an
octal number. When they then encounter <code>9</code> (which is not an octal digit), they will stop
parsing and discard the rest of the string, returning the value <code>0</code>, which is probably not
what was expected.
</p>
<p>
To avoid this problem, an explicit radix parameter should be parsed as follows:
</p>
<sample src="examples/ParseIntRadixGood.js" />
</example>
<references>
<li>D. Crockford, <i>JavaScript: The Good Parts</i>, Appendix A.7. O'Reilly, 2008.</li>
</references>
</qhelp>