I'm writing a parser that converts the output of a command into a JSON object that I can push to a realtime logging and graphing service. Everything comes out of the parser as strings, and I'd like numbers to come out as numbers, but I'm having a small problem.
I know that parseInt(string) returns NaN if you use a non-parseable string. The problem I have is that the string '802.11 auth' can be parsed by parseInt to 802, which is definitely not what I want.
wat do. I'm currently hacking it by checking the last character in the string, but it's an inelegant solution.
blackjack:~ sent1nel$ cat whatever.js
console.log(parseInt("802.11 auth"));
blackjack:~ sent1nel$ node whatever.js
802
You can use the unary plus operator to convert a string rather than parsing it:
+"802.11" // 802.11
+"802.11 auth" // NaN
If you only want to know if a variable is a number:
var s = "802.11 auth";
s == +s
> false // the string s is not convertible into a number
var s2 = "802.11";
s2 == +s2
> true // the string s2 is convertible into a number
If you want to extract the number:
var s = "802.11 auth";
var number1 = + s.match(/[\d.]/g).join(''); // 802.11
var number2 = Number(s.match(/[\d.]/g).join('')); // 802.11
If you only want 802 you can use parseInt():
var number3 = parseInt(s.match(/[\d.]/g).join('')); // 802