I saw this thread, 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 for ""
?
相关问题
- Is there a limit to how many levels you can nest i
- How to toggle on Order in ReactJS
- void before promise syntax
- Keeping track of variable instances
- Can php detect if javascript is on or not?
Don't assume that the variable you check is a string. Don't assume that if this var has a length, then it's a string.
The thing is: think carefully about what your app must do and can accept. Build something robust.
If your method / function should only process a non empty string then test if the argument is a non empty string and don't do some 'trick'.
As an example of something that will explode if you follow some advices here not carefully.
So, I'd stick with
Also, in case you consider a whitespace filled string as "empty". You can test it with this Regex:
All these answers are nice.
But I cannot be sure that variable is a string, doesn't contains only spaces (this is important for me), and can contain '0' (string).
My version:
Sample on jsfiddle.
I would not worry too much about the most efficient method. Use what is most clear to your intention. For me that's usually
strVar == ""
.EDIT: per comment from Constantin, if strVar could some how end up containing an integer 0 value, then that would indeed be one of those intention-clarifying situations.
I use a combination, fastest checks are first.
you could also go with regexps:
Checks for strings that are either empty or filled with whitespace.