17 Jan 2017 09:50 +0000
You can convert a string to an integer using the built-in parseInt() function. This takes the base for the conversion as an optional second argument, which you should always provide:
parseInt("123", 10); // 123
parseInt("010", 10); // 10
In older browsers, strings beginning with a "0" are assumed to be in octal (radix 8), but this hasn't been the case since 2013 or so. Unless you're certain of your string format, you can get surprising results on those older browsers:
parseInt("010"); // 8
parseInt("0x10"); // 16
Here, we see the parseInt() function treat the first string as octal due to the leading 0, and the second string as hexadecimal due to the leading "0x". The hexadecimal notation is still in place; only octal has been removed.
If you want to convert a binary number to an integer, just change the base:
parseInt("11", 2); // 3
Loading comments...