While the question of checking for null or undefined values has been raised before, I am encountering a unique issue. I have created a function to split a string, which works perfectly. However, when I pass a null or undefined value, the program stops. Instead of halting, I would like it to return an empty string.
splitString(str: string, length: number) {
if (str != null && str != undefined){
var words = str.split(" ");
for (var j = 0; j < words.length; j++) {
var l = words[j].length;
if (l > length) {
var result = [], i = 0;
while (i < l) {
result.push(words[j].substr(i, length))
i += length;
}
words[j] = result.join(" ");
}
}
return words.join(" ");
}
else if (typeof(str) === null ){
return " "
}
}
Previously, the program would stop with an error message when encountering a null value, but now it is able to handle it gracefully by returning an empty string. Thank you for the help.