I saw this thread, but I didn't see a JavaScript specific example. Is there a simple string.Empty in JavaScript, or is it just checking for "" ?
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).
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 some how ended up containing an integer 0 value, then strVar == ""
returns true. So if that is a danger in your situation, you should code strVar === ""
, which ensures that the types are also the same.
var s; // undefined
var s = ""; // ""
s.length // 0
There's nothing representing an empty string in JavaScript. Do a check against either length
(if you know that the var will always be a string) or against ""
The closest thing you can get to str.Empty (with the precondition that str is a String) is:
if (!str.length) { ...
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,"") == ""){
}
just FYI, i think the most useful APIs for the String class are at Mozilla and javascript kit. elated.com has a tutorial on all of String's properties, methods,...
I usually use something like:
if (str == "") {
//Do Something
}
else {
//Do Something Else
}
you could also go with regexps:
if((/^\s*$/).test(str)) { }
Checks for strings that are either empty or filled with whitespace.
I use :
function empty(e) {
switch(e) {
case "":
case 0:
case "0":
case null:
case false:
case typeof this == "undefined":
return true;
default : return false;
}
}
empty(null) // true
empty(0) // true
empty(7) // false
empty("") // true
empty((function() { return "" }) ) // true
For checking if a string is empty, null or undefined I use:
function isEmpty(str) {
return (!str || 0 === str.length);
}
For checking if a string is blank, null or undefined I use:
function isBlank(str) {
return (!str || /^\s*$/.test(str));
}
function tell()
{
var pass = document.getElementById('pasword').value;
var plen = pass.length;
now you can check if your string is empty as like
if(plen==0)
{
alert('empty');
}
else
{
alert('you entered something');
}
}
<input type='text' id='pasword' />
this is also a generic way to check if field is empty.