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

1 Answer

0 votes
function isBlankOrEmpty(str) {
    // 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 = [null, "", "   ", "node.js", ".", "123"];

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




/*
run:

Test1: true
Test2: true
Test3: true
Test4: false
Test5: false
Test6: false

*/

 



answered Jun 7 by avibootz
...