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

后端 未结 30 4138
长发绾君心
长发绾君心 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条回答
  •  旧时难觅i
    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

提交回复
热议问题