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

后端 未结 30 4103
长发绾君心
长发绾君心 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:01

    Starting with:

    return (!value || value == undefined || value == "" || value.length == 0);
    

    Looking at the last condition, if value == "", its length must be 0. Therefore drop it:

    return (!value || value == undefined || value == "");
    

    But wait! In JavaScript, an empty string is false. Therefore, drop value == "":

    return (!value || value == undefined);
    

    And !undefined is true, so that check isn't needed. So we have:

    return (!value);
    

    And we don't need parentheses:

    return !value
    
    0 讨论(0)
  • 2020-11-22 00:01

    I have not noticed an answer that takes into account the possibility of null characters in a string. For example, if we have a null character string:

    var y = "\0"; // an empty string, but has a null character
    (y === "") // false, testing against an empty string does not work
    (y.length === 0) // false
    (y) // true, this is also not expected
    (y.match(/^[\s]*$/)) // false, again not wanted
    

    To test its nullness one could do something like this:

    String.prototype.isNull = function(){ 
      return Boolean(this.match(/^[\0]*$/)); 
    }
    ...
    "\0".isNull() // true
    

    It works on a null string, and on an empty string and it is accessible for all strings. In addition, it could be expanded to contain other JavaScript empty or whitespace characters (i.e. nonbreaking space, byte order mark, line/paragraph separator, etc.).

    0 讨论(0)
  • 2020-11-22 00:01

    Meanwhile we can have one function that checks for all 'empties' like null, undefined, '', ' ', {}, []. So I just wrote this.

    var isEmpty = function(data) {
        if(typeof(data) === 'object'){
            if(JSON.stringify(data) === '{}' || JSON.stringify(data) === '[]'){
                return true;
            }else if(!data){
                return true;
            }
            return false;
        }else if(typeof(data) === 'string'){
            if(!data.trim()){
                return true;
            }
            return false;
        }else if(typeof(data) === 'undefined'){
            return true;
        }else{
            return false;
        }
    }
    

    Use cases and results.

    console.log(isEmpty()); // true
    console.log(isEmpty(null)); // true
    console.log(isEmpty('')); // true
    console.log(isEmpty('  ')); // true
    console.log(isEmpty(undefined)); // true
    console.log(isEmpty({})); // true
    console.log(isEmpty([])); // true
    console.log(isEmpty(0)); // false
    console.log(isEmpty('Hey')); // false
    
    0 讨论(0)
  • 2020-11-22 00:01

    Try this:

    export const isEmpty = string => (!string || !string.length);
    
    0 讨论(0)
  • 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());
    };
    
    0 讨论(0)
  • 2020-11-22 00:03

    I did some research on what happens if you pass a non-string and non-empty/null value to a tester function. As many know, (0 == "") is true in JavaScript, but since 0 is a value and not empty or null, you may want to test for it.

    The following two functions return true only for undefined, null, empty/whitespace values and false for everything else, such as numbers, Boolean, objects, expressions, etc.

    function IsNullOrEmpty(value)
    {
        return (value == null || value === "");
    }
    function IsNullOrWhiteSpace(value)
    {
        return (value == null || !/\S/.test(value));
    }
    

    More complicated examples exists, but these are simple and give consistent results. There is no need to test for undefined, since it's included in (value == null) check. You may also mimic C# behaviour by adding them to String like this:

    String.IsNullOrEmpty = function (value) { ... }
    

    You do not want to put it in Strings prototype, because if the instance of the String-class is null, it will error:

    String.prototype.IsNullOrEmpty = function (value) { ... }
    var myvar = null;
    if (1 == 2) { myvar = "OK"; } // Could be set
    myvar.IsNullOrEmpty(); // Throws error
    

    I tested with the following value array. You can loop it through to test your functions if in doubt.

    // Helper items
    var MyClass = function (b) { this.a = "Hello World!"; this.b = b; };
    MyClass.prototype.hello = function () { if (this.b == null) { alert(this.a); } else { alert(this.b); } };
    var z;
    var arr = [
    // 0: Explanation for printing, 1: actual value
        ['undefined', undefined],
        ['(var) z', z],
        ['null', null],
        ['empty', ''],
        ['space', ' '],
        ['tab', '\t'],
        ['newline', '\n'],
        ['carriage return', '\r'],
        ['"\\r\\n"', '\r\n'],
        ['"\\n\\r"', '\n\r'],
        ['" \\t \\n "', ' \t \n '],
        ['" txt \\t test \\n"', ' txt \t test \n'],
        ['"txt"', "txt"],
        ['"undefined"', 'undefined'],
        ['"null"', 'null'],
        ['"0"', '0'],
        ['"1"', '1'],
        ['"1.5"', '1.5'],
        ['"1,5"', '1,5'], // Valid number in some locales, not in JavaScript
        ['comma', ','],
        ['dot', '.'],
        ['".5"', '.5'],
        ['0', 0],
        ['0.0', 0.0],
        ['1', 1],
        ['1.5', 1.5],
        ['NaN', NaN],
        ['/\S/', /\S/],
        ['true', true],
        ['false', false],
        ['function, returns true', function () { return true; } ],
        ['function, returns false', function () { return false; } ],
        ['function, returns null', function () { return null; } ],
        ['function, returns string', function () { return "test"; } ],
        ['function, returns undefined', function () { } ],
        ['MyClass', MyClass],
        ['new MyClass', new MyClass()],
        ['empty object', {}],
        ['non-empty object', { a: "a", match: "bogus", test: "bogus"}],
        ['object with toString: string', { a: "a", match: "bogus", test: "bogus", toString: function () { return "test"; } }],
        ['object with toString: null', { a: "a", match: "bogus", test: "bogus", toString: function () { return null; } }]
    ];
    
    0 讨论(0)
提交回复
热议问题