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

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

    As of now there is no direct method like string.empty to check whether a string is empty or not. But in your code you can use a wrapper check for an empty string like:

    // considering the variable in which your string is saved is named str.
    
    if (str && str.length>0) { 
    
      // Your code here which you want to run if the string is not empty.
    
    }
    

    Using this you can also make sure that string is not undefined or null too. Remember, undefined, null and empty are three different things.

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

    To check if it is exactly an empty string:

    if(val==="")...
    

    To check if it is an empty string OR a logical equivalent for no-value (null, undefined, 0, NaN, false, ...):

    if(!val)...
    
    0 讨论(0)
  • 2020-11-22 00:15

    Performance

    I perform tests on macOS v10.13.6 (High Sierra) for 18 chosen solutions. Solutions works slightly different (for corner-case input data) which was presented in the snippet below.

    Conclusions

    • the simple solutions based on !str,==,=== and length are fast for all browsers (A,B,C,G,I,J)
    • the solutions based on the regular expression (test,replace) and charAt are slowest for all browsers (H,L,M,P)
    • the solutions marked as fastest was fastest only for one test run - but in many runs it changes inside 'fast' solutions group

    Details

    In the below snippet I compare results of chosen 18 methods by use different input parameters

    • "" "a" " "- empty string, string with letter and string with space
    • [] {} f- array, object and function
    • 0 1 NaN Infinity - numbers
    • true false - Boolean
    • null undefined

    Not all tested methods support all input cases.

    function A(str) {
      let r=1;
      if (!str)
        r=0;
      return r;
    }
    
    function B(str) {
      let r=1;
      if (str == "")
        r=0;
      return r;
    }
    
    function C(str) {
      let r=1;
      if (str === "")
        r=0;
      return r;
    }
    
    function D(str) {
      let r=1;
      if(!str || 0 === str.length)
        r=0;
      return r;
    }
    
    function E(str) {
      let r=1;
      if(!str || /^\s*$/.test(str))
        r=0;
      return r;
    }
    
    function F(str) {
      let r=1;
      if(!Boolean(str))
        r=0;
      return r;
    }
    
    function G(str) {
      let r=1;
      if(! ((typeof str != 'undefined') && str) )
        r=0;
      return r;
    }
    
    function H(str) {
      let r=1;
      if(!/\S/.test(str))
        r=0;
      return r;
    }
    
    function I(str) {
      let r=1;
      if (!str.length)
        r=0;
      return r;
    }
    
    function J(str) {
      let r=1;
      if(str.length <= 0)
        r=0;
      return r;
    }
    
    function K(str) {
      let r=1;
      if(str.length === 0 || !str.trim())
        r=0;
      return r;
    }
    
    function L(str) {
      let r=1;
      if ( str.replace(/\s/g,"") == "")
        r=0;
      return r;
    }
    
    function M(str) {
      let r=1;
      if((/^\s*$/).test(str))
        r=0;
      return r;
    }
    
    
    function N(str) {
      let r=1;
      if(!str || !str.trim().length)
        r=0;
      return r;
    }
    
    function O(str) {
      let r=1;
      if(!str || !str.trim())
        r=0;
      return r;
    }
    
    function P(str) {
      let r=1;
      if(!str.charAt(0))
        r=0;
      return r;
    }
    
    function Q(str) {
      let r=1;
      if(!str || (str.trim()==''))
        r=0;
      return r;
    }
    
    function R(str) {
      let r=1;
      if (typeof str == 'undefined' ||
          !str ||
          str.length === 0 ||
          str === "" ||
          !/[^\s]/.test(str) ||
          /^\s*$/.test(str) ||
          str.replace(/\s/g,"") === "")
    
        r=0;
      return r;
    }
    
    
    
    
    // --- TEST ---
    
    console.log(                  '   ""  "a"  " " [] {} 0 1 NaN Infinity f true false null undefined ');
    let log1 = (s,f)=> console.log(`${s}: ${f("")}   ${f("a")}    ${f(" ")}   ${f([])}  ${f({})}  ${f(0)} ${f(1)} ${f(NaN)}   ${f(Infinity)}        ${f(f)} ${f(true)}    ${f(false)}     ${f(null)}    ${f(undefined)}`);
    let log2 = (s,f)=> console.log(`${s}: ${f("")}   ${f("a")}    ${f(" ")}   ${f([])}  ${f({})}  ${f(0)} ${f(1)} ${f(NaN)}   ${f(Infinity)}        ${f(f)} ${f(true)}    ${f(false)}`);
    let log3 = (s,f)=> console.log(`${s}: ${f("")}   ${f("a")}    ${f(" ")}`);
    
    log1('A', A);
    log1('B', B);
    log1('C', C);
    log1('D', D);
    log1('E', E);
    log1('F', F);
    log1('G', G);
    log1('H', H);
    
    log2('I', I);
    log2('J', J);
    
    log3('K', K);
    log3('L', L);
    log3('M', M);
    log3('N', N);
    log3('O', O);
    log3('P', P);
    log3('Q', Q);
    log3('R', R);

    And then for all methods I perform speed test case str = "" for browsers Chrome v78.0.0, Safari v13.0.4, and Firefox v71.0.0 - you can run tests on your machine here

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

    A lot of answers, and a lot of different possibilities!

    Without a doubt for quick and simple implementation the winner is: if (!str.length) {...}

    However, as many other examples are available. The best functional method to go about this, I would suggest:

    function empty(str)
    {
        if (typeof str == 'undefined' || !str || str.length === 0 || str === "" || !/[^\s]/.test(str) || /^\s*$/.test(str) || str.replace(/\s/g,"") === "")
            return true;
        else
            return false;
    }

    A bit excessive, I know.

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

    I use:

    function empty(e) {
      switch (e) {
        case "":
        case 0:
        case "0":
        case null:
        case false:
        case typeof(e) == "undefined":
          return true;
        default:
          return false;
      }
    }
    
    empty(null) // true
    empty(0) // true
    empty(7) // false
    empty("") // true
    empty((function() {
        return ""
    })) // false
    
    0 讨论(0)
  • 2020-11-22 00:19

    Try:

    if (str && str.trim().length) {  
        //...
    }
    
    0 讨论(0)
提交回复
热议问题