How can I check for an empty/undefined/null string in JavaScript?

后端 未结 30 4841
长发绾君心
长发绾君心 2020-11-21 23:47

I saw this question, but I didn\'t see a JavaScript specific example. Is there a simple string.Empty available in JavaScript, or is it just a case of checking f

30条回答
  •  生来不讨喜
    2020-11-22 00:02

    For checking if a string is empty, null or undefined I use:

    function isEmpty(str) {
        return (!str || 0 === str.length);
    }
    

    For checking if a string is blank, null or undefined I use:

    function isBlank(str) {
        return (!str || /^\s*$/.test(str));
    }
    

    For checking if a string is blank or contains only white-space:

    String.prototype.isEmpty = function() {
        return (this.length === 0 || !this.trim());
    };
    

提交回复
热议问题