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

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

    As of now there is no direct method like string.empty to check whether a string is empty or not. But in your code you can use a wrapper check for an empty string like:

    // considering the variable in which your string is saved is named str.
    
    if (str && str.length>0) { 
    
      // Your code here which you want to run if the string is not empty.
    
    }
    

    Using this you can also make sure that string is not undefined or null too. Remember, undefined, null and empty are three different things.

提交回复
热议问题