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

后端 未结 30 4100
长发绾君心
长发绾君心 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-21 23:58

    If you just want to check whether there's any value, you can do

    if (strValue) {
        //do something
    }
    

    If you need to check specifically for an empty string over null, I would think checking against "" is your best bet, using the === operator (so that you know that it is, in fact, a string you're comparing against).

    if (strValue === "") {
        //...
    }
    
    0 讨论(0)
  • 2020-11-21 23:58

    If you need to make sure that the string is not just a bunch of empty spaces (I'm assuming this is for form validation) you need to do a replace on the spaces.

    if(str.replace(/\s/g,"") == ""){
    }
    
    0 讨论(0)
  • 2020-11-21 23:58

    I didn't see a good answer here (at least not an answer that fits for me)

    So I decided to answer myself:

    value === undefined || value === null || value === "";

    You need to start checking if it's undefined. Otherwise your method can explode, and then you can check if it equals null or is equal to an empty string.

    You cannot have !! or only if(value) since if you check 0 it's going to give you a false answer (0 is false).

    With that said, wrap it up in a method like:

    public static isEmpty(value: any): boolean { return value === undefined || value === null || value === ""; }

    PS.: You don't need to check typeof, since it would explode and throw even before it enters the method

    0 讨论(0)
  • 2020-11-21 23:58

    Try this

    str.value.length == 0
    
    0 讨论(0)
  • 2020-11-22 00:01

    All the previous answers are good, but this will be even better. Use dual NOT operators (!!):

    if (!!str) {
        // Some code here
    }
    

    Or use type casting:

    if (Boolean(str)) {
        // Code here
    }
    

    Both do the same function. Typecast the variable to Boolean, where str is a variable.
    It returns false for null, undefined, 0, 000, "", false.
    It returns true for string "0" and whitespace " ".

    0 讨论(0)
  • 2020-11-22 00:01

    I usually use something like this,

    if (!str.length) {
        // Do something
    }
    
    0 讨论(0)
提交回复
热议问题