What is the best way to test for an empty string with jquery-out-of-the-box?

后端 未结 10 814
Happy的楠姐
Happy的楠姐 2020-11-29 15:45

What is the best way to test for an empty string with jquery-out-of-the-box, i.e. without plugins? I tried this.

But it did\'t work at least out-of-the-box. It woul

相关标签:
10条回答
  • 2020-11-29 16:19

    Try executing this in your browser console or in a node.js repl.

    var string = ' ';
    string ? true : false;
    //-> true
    
    string = '';
    string ? true : false;
    //-> false
    

    Therefore, a simple branching construct will suffice for the test.

    if(string) {
        // string is not empty
    }
    
    0 讨论(0)
  • 2020-11-29 16:22
    if (!a) {
      // is emtpy
    }
    

    To ignore white space for strings:

    if (!a.trim()) {
        // is empty or whitespace
    }
    

    If you need legacy support (IE8-) for trim(), use $.trim or a polyfill.

    0 讨论(0)
  • 2020-11-29 16:23
    if(!my_string){ 
    // stuff 
    }
    

    and

    if(my_string !== "")
    

    if you want to accept null but reject empty

    EDIT: woops, forgot your condition is if it IS empty

    0 讨论(0)
  • 2020-11-29 16:25

    Based on David's answer I personally like to check the given object first if it is a string at all. Otherwise calling .trim() on a not existing object would throw an exception:

    function isEmpty(value) {
      return typeof value == 'string' && !value.trim() || typeof value == 'undefined' || value === null;
    }
    

    Usage:

    isEmpty(undefined); // true
    isEmpty(null); // true
    isEmpty(''); // true
    isEmpty('foo'); // false
    isEmpty(1); // false
    isEmpty(0); // false
    
    0 讨论(0)
提交回复
热议问题