How to check if a string is blank (empty, null, or contains only whitespace) in TypeScript

1 Answer

0 votes
function isBlankOrEmpty(str: string | null): boolean {
    // Check for null or empty string
    if (str === null || str === "") {
        return true;
    }

    // Check if the string contains only whitespace
    for (let char of str) {
        if (!/\s/.test(char)) {
            return false; // Found a non-whitespace character
        }
    }
    
    return true;
}

const testCases : (string | null)[] = [null, "", "   ", "abc"];

testCases.forEach((test: string | null, index) => {
    console.log(`Test${index + 1}: ${isBlankOrEmpty(test)}`);
});



/*
run:

"Test1: true" 
"Test2: true" 
"Test3: true" 
"Test4: false" 

*/

 



answered Jun 7, 2025 by avibootz
...