Check if string is not null or empty javascript




















Active Oldest Votes. You can simply use typeof. It will check undefined, null, 0 and "" also. Improve this answer. Parveen Sachdeva Parveen Sachdeva 2 2 gold badges 17 17 silver badges 26 26 bronze badges.

What difference is there between your code and simply if RetailPrice? Shouldn't you use! This is the wrong answer, it doesn't work with strings. TS throws an exception: Type 'string' is not assignable to type 'boolean'. Show 1 more comment. To excludes blank strings as well if this. Asanka Siriwardena Asanka Siriwardena 12 12 silver badges 17 17 bronze badges.

CarbonDonuts CarbonDonuts 55 4 4 bronze badges. Int — Andreas Louv. You could very well use a double negative. Sign up or log in Sign up using Google. Sign up using Facebook. Sign up using Email and Password. Post as a guest Name. Email Required, but never shown. The Overflow Blog. Stack Gives Back Safety in numbers: crowdsourcing data on nefarious IP addresses. Featured on Meta. New post summary designs on greatest hits now, everywhere else eventually. Visit chat. Related Are you using it as a convention or is there an example where you can get unexpected results?

Don't forget to trim if! Show 5 more comments. Tom Castle Tom Castle 2, 1 1 gold badge 16 16 silver badges 20 20 bronze badges. JeanValjean Christopher Richa Christopher Richa 1, 1 1 gold badge 8 8 silver badges 20 20 bronze badges. Actually I was going to edit this before it got closed: if! Empty is not null. What is the source where you found this info? What if str is undefined? If you're checking falsiness, your best bet is if! But if you're checking for empty string, as per the question, I think nxt's is the best.

This answer is miscorrect because the condition gonna be truthy even if variable str is null , while null is an object type, not string. Third, I would remove the! They are redundant. This checks if the type of the value is "string" and thus non-null and not undefined , and if it is not empty. If so, it is not null or empty. Note that this returns true for non-string inputs, which might not be what you want if you wanted to throw an error for an unexpected input type. It's quite possible that!

But if you create a function that is named isNullOrEmpty , then it should do just that. You should use Object. This ties it to the String object in all instances. This would start to give you access to use strings and variables like "". If your intent is to use it as a function to pass in variables: String. Sign up to join this community. The best answers are voted up and rise to the top.

Stack Overflow for Teams — Collaborate and share knowledge with a private group. Create a free Team What is Teams?



0コメント

  • 1000 / 1000