jquery - Parse an integer (and *only* an integer) in JavaScript -
prompt possible translate string number variant except integer produced error.
func('17') = 17; func('17.25') = nan func(' 17') = nan func('17test') = nan func('') = nan func('1e2') = nan func('0x12') = nan
parseint not work, because not work correctly.
parseint('17') = 17; parseint('17.25') = 17 // incorrect parseint(' 17') = nan parseint('17test') = 17 // incorrect parseint('') = nan parseint('1e2') = 1 // incorrect
and importantly: function work in ie, chrome , other browsers!!!
you can use regular expression , ternary operator reject strings containing non-digits:
function intornan (x) { return /^\d+$/.test(x) ? +x : nan } console.log([ '17', //=> 17 '17.25', //=> nan ' 17', //=> nan '17test', //=> nan '', //=> nan '1e2', //=> nan '0x12' //=> nan ].map(intornan))
Comments
Post a Comment