How to check if a variable is null or empty string or all whitespace in JavaScript?

后端 未结 12 1341
失恋的感觉
失恋的感觉 2020-12-23 13:05

I need to check to see if a variable is null or has all empty spaces or is just blank (\"\").

I have the following, but it is not working:

var addr;
         


        
相关标签:
12条回答
  • 2020-12-23 13:35

    When checking for white space the c# method uses the Unicode standard. White space includes spaces, tabs, carriage returns and many other non-printing character codes. So you are better of using:

    function isNullOrWhiteSpace(str){
        return str == null || str.replace(/\s/g, '').length < 1;
    }
    
    0 讨论(0)
  • 2020-12-23 13:40

    You can use if(addr && (addr = $.trim(addr)))

    This has the advantage of actually removing any outer whitespace from addr instead of just ignoring it when performing the check.

    Reference: http://api.jquery.com/jQuery.trim/

    0 讨论(0)
  • 2020-12-23 13:41

    You can try this:

    do {
       var op = prompt("please input operatot \n you most select one of * - / *  ")
    } while (typeof op == "object" || op == ""); 
    // execute block of code when click on cancle or ok whthout input
    
    0 讨论(0)
  • 2020-12-23 13:43

    Simplified version of the above: (from here: https://stackoverflow.com/a/32800728/47226)

    function isNullOrWhitespace( input ) {
      return !input || !input.trim();
    }
    
    0 讨论(0)
  • 2020-12-23 13:44
    isEmptyOrSpaces(str){
        return str === null || str.trim().length>0;
    }
    
    0 讨论(0)
  • 2020-12-23 13:47

    Old question, but I think it deservers a simpler answer.

    You can simply do:

    var addr = "  ";
    
    if (addr && addr.trim()) {
    
        console.log("I'm not null, nor undefined, nor empty string, nor string composed of whitespace only.");
    
    }
    
    0 讨论(0)
提交回复
热议问题