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

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

    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.).

提交回复
热议问题