Search code examples
javascriptnulldouble-quotes

javascript handling treating double quotes as empty string


Trying to modify the following function to handle additional requests.

function not working when datatype is object and has quotes in it, which needs to be treated as empty

 //try to handle double quotes as empty
 // "\"\""        true, empty string
 // ''''        true, empty string

// test results
//---------------
// []        true, empty array
// {}        true, empty object
// null      true
// undefined true
// ""        true, empty string
// ''        true, empty string
// null      true
// true      false, boolean
// false     false, boolean
// Date      false
// function  false


function empty ( val ) {

  if  (typeof val === undefined)
    return true;

  if (typeof (val) == 'function' || typeof (val) == 'number' || typeof (val) == 'boolean' || Object.prototype.toString.call(val) === '[object Date]')
    return false;

  if (val == null || val == '' || val.length === 0) // null or empty string or 0 length array
    return true;

  if (typeof (val) == "object") {
    // empty object
    var r = true;
    for (var f in val) {
        r = false;
    }
    return r;
  }

  return false;
}

Solution

  • /^(""|'')$/.test(val)

    if (/^(""|'')$/.test(val) || val == null || val == '' || val.length === 0)
        return true;
    

    you can shorten your conditions by checking for an empty string in the regex:

    if (/^(""|''|)$/.test(val) || val == null)
        return true;