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

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

提交回复
热议问题