Custom Parse Int
Parse a string into a number. If a char string is attached return not a number or if number is floating point
by Andrew Corliss
JavaScript
function myParseInt(str) {
var newStr = str.replace(' ', '');
var integer = 0;
if (newStr.match(/[a-z]+/i) || newStr.match(/\s[0-9]+/g) >= 2) {
integer = NaN;
} else if (newStr.replace(/[0-9]+/g, '')[0] == 0 && !newStr.replace(/[0-9]+/g, '')[1]) {
integer = 0;
} else {
var endStr = newStr.split('.');
integer = Number(endStr[0].replace(/\D/g, ''));
}
return integer;
}
console.log(myParseInt("1"));
console.log(myParseInt(" 1 "));
console.log(myParseInt("08"));
console.log(myParseInt("16.5"));
console.log(myParseInt("2 friends"));