typeof example
by Larry Adams
JavaScript
console.clear();
function truncate(inputString, targetLength){
if (typeof inputString == 'String' && typeof targetLength == 'Number') {
console.log("I am here - 1");
return inputString.substr(0, targetLength);
} else if (typeof inputString == 'string') {
console.log("I am here - 2");
return inputString.substr(0, targetLength);
} else if (typeof inputString == 'undefined') {
console.log("I am here - 3");
return 'Invalid Input';
} else if (isNaN(parseInt(targetLength))) {
console.log("I am here - 4");
return 'Invalid Input';
} else {
console.log("I am here - 5");
return targetLength;
}
}
//test cases
var x = "Fourscore and seven years ago";
var y;
console.log("1: " + truncate(x, 10));
document.getElementById("1").innerHTML = "1: " + truncate(x, 10);
console.log("2: " + truncate(x)); // should output the unmodified string
document.getElementById("2").innerHTML = "2: " + truncate(x);
console.log("3: " + truncate(10, 10));
document.getElementById("3").innerHTML = "3: " + truncate(10, 10);
console.log("4: " + truncate(y, 10));
document.getElementById("4").innerHTML = "4: " + truncate(y, 10);
console.log("5: " + truncate(x, "Bob"));
document.getElementById("5").innerHTML = "5: " + truncate(x, "Bob");