Prompt as it is possible to translate a string to number so that only any variant except for the integer produced an error.
func('17') = 17;
func('17.25') = NaN
func(' 17') = NaN
func('17test') = NaN
func('') = NaN
func('1e2') = NaN
func('0x12') = NaN
ParseInt does not work, because it does 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 most importantly: for the function to work in IE, Chrome and other browsers!!!
Prompt as it is possible to translate a string to number so that only any variant except for the integer produced an error.
func('17') = 17;
func('17.25') = NaN
func(' 17') = NaN
func('17test') = NaN
func('') = NaN
func('1e2') = NaN
func('0x12') = NaN
ParseInt does not work, because it does 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 most importantly: for the function to work in IE, Chrome and other browsers!!!
Share Improve this question edited Apr 14, 2017 at 19:39 gyre 16.8k4 gold badges40 silver badges47 bronze badges asked Apr 14, 2017 at 19:24 ZhiharZhihar 1,4283 gold badges25 silver badges48 bronze badges 1- Number() will get you close, but do you want to discard decimal places or do you really want to reject them as NaN? – Christopher Commented Apr 14, 2017 at 19:27
2 Answers
Reset to default 14You can use a regular expression and the ternary operator to reject all 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))
This would satisfy all your tests:
function func (str) {
var int = parseInt(str, 10);
return str == str.trim() && str == int ? int : NaN
}