Verify if the variable is a non-empty string in JavaScript


This content was proof-read by Grammarly. You can Try Grammary for FREE

If you want to test if a variable that is defined is a non-empty string in JavaScript , you can use the typeof keyword to find if the type is a sring as well as check for the length of the string as shown below.

How to verify if the variable is a non-empty string in JavaScript ?

<script>
    var input = 'This is a test string';
    if (typeof input === 'string' && input.length > 0) {
        console.log('valid non-empty string');
    } else {
        console.log('Invalid string input');
    }
</script>

This will cause the else part to execute if the variable is non-empty string.

Newsletter Signup

Subscribe to our weekly newsletter below and never miss the latest product or an exclusive offer.

Newsletter Signup

Subscribe to our weekly newsletter below and never miss the latest product or an exclusive offer.

%d bloggers like this: