Parsing Strings to Integers
How to use Number.parseInt and Number primitive wrapper object to parse strings to integers.
So the first option we’re going to look at is parsing ints through the parseInt function and the parseInt function exists as both a global function as well as a method on the Number primitive wrapper object or the the Number global object. When we’re parsing the int, numbers can exist in a couple different forms depending on whether they’re representing a hexadecimal number or a binary number or maybe an octal number.
So when we look at a string that has a “0x” in the front, when we use parseInt there’s two arguments we need to pass in. The first one is the string itself and then the second one is the radix. If we do parseInt and then some value you know there’s an optional parameter here where we can specify the base of the number. If we were to parseInt with 0x16 the radix would default to 16 because the string is a hexadecimal representation of the number. If one is not provided, in older browsers, the radix could either be 8 or 10 and it was implementation specific. So a best practice was always to specify the the radix that you wanted to use just so you didn’t leave it to chance depending on the user’s browser. But starting with ES5 the 10 is the default radix when we use parseInt so it will always assume it is a decimal number. When we pass in a string that has white space either on the left or the right when it’s coercing then when it’s parsing through this string it will trim off the white space on either end and parse the integer correctly. If there’s a leading zero it will trim that as well. If we pass in a string that has a integer component in the front, such as in this case maybe the string representation of 15 pixels, it will parse up to the first non-numeral digit that’s not also specified by the radix right. So recall up here with this 0x16 you know it continued to parse this string because x is one of the non-numeral characters that it will include as part of the parsing. So here you can see it got up to the “p” from pixels and then it stopped parsing and gave us the value of 15. This behaves mostly how you expect, I think the the one point that could trip you up is that if you have a kind of garbled string that gets passed in here and it happens to start with a few integers you know it may parse it in a way that you may not be expecting. You may expect it to throw an error but it will try its best to parse it and in some cases that may give you some undefined behavior.
So there’s definitely a lot to explore here but hopefully this will give you a good introduction so that if you run into one of these scenarios where you know you need to parse through an html html attribute or a form value that this will give you the tools that you need.