Check String is Exist or NonEmpty String in JavaScript Example

Updated on     Kisan Patel

Check that a variable is defined, is a string, and is not empty.

The typeof operator

// true if variable exists, is a string, and has a length greater than zero
if(((typeof unknownVariable != "undefined") &&
    (typeof unknownVariable.valueOf() == "string")) &&
    (unknownVariable.length > 0)) {

        ...

    }

The JavaScript typeof operator returns the type of a variable.

// succeeds if string with length greater than zero
if ((typeof unknownVariable == "string") && (unknownVariable.length > 0)) {
...
}

The length method

if (strFromFormElement.length == 0) // testing for empty string

JavaScript

Leave a Reply