While looking at adding a trim function to the String prototype, I came across something that seems odd to me with JavaScript strings.
if (typeof console === 'undefined') {
var console = { };
console.log = function(msg) {
alert(msg)
}
}
function isString(str) {
return ((str && typeof str === 'string') ||
(str && (str.constructor == String && (str.toString() !== 'null' && str.toString() !== 'undefined'))));
}
if (!String.prototype.trim) {
String.prototype.trim = function () {
return this.replace(/^\s*(\S*(?:\s+\S+)*)\s*$/, "$1");
};
}
function testing (str) {
if (isString(str)) {
console.log("Trimmed: " + str.trim() + " Length: " + str.trim().length);
} else {
console.log("Type of: " + typeof str);
}
return false;
}
function testSuite() {
testing(undefined);
testing(null);
testing("\t\r\n");
testing(" 90909090");
testing("lkkljlkjlkj ");
testing(" 12345 ");
testing("lkjfsdaljkdfsalkjdfs");
testing(new String(undefined)); //Why does this create a string with value 'undefined'
testing(new String(null)); //Why does this create a string with value 'null'
testing(new String("\t\r\n"));
testing(new String(" 90909090"));
testing(new String("lkkljlkjlkj "));
testing(new String(" 12345 "));
testing(new String("lkjfsdaljkdfsalkjdfs"));
}
Now I know that we shouldn't be creating Strings with the new operator, but I'd hate to have someone call this on an undefined or null string that was created more along the lines of:
new String ( someUndefinedOrNullVar );
What am I missing? Or is the !== 'null' && !== 'undefined' check really necessary (Removing that check, will show 'null' and 'undefined')?