Is there a string.Empty in JavaScript, or is it just a case of checking for ""?
56 Answers
There's no isEmpty() method, you have to check for the type and the length:
if (typeof test === 'string' && test.length === 0){
...
The type check is needed in order to avoid runtime errors when test is undefined or null.
1 Comment
test === "" is equivalent, and it's shorter.Ignoring whitespace strings, you could use this to check for null, empty and undefined:
var obj = {};
(!!obj.str) // Returns false
obj.str = "";
(!!obj.str) // Returns false
obj.str = null;
(!!obj.str) // Returns false
It is concise and it works for undefined properties, although it's not the most readable.
1 Comment
undefined or nullI usually use something like:
if (str == "") {
//Do Something
}
else {
//Do Something Else
}
1 Comment
== operator is not strict. So if str == "", str can be null, undefined, false, 0, [], etc..Try this
str.value.length == 0
2 Comments
"".value.length will cause an error. It should be str.length === 0TypeError If str is equal to undefined or nullYou can easily add it to native String object in JavaScript and reuse it over and over...
Something simple like below code can do the job for you if you want to check '' empty strings:
String.prototype.isEmpty = String.prototype.isEmpty || function() {
return !(!!this.length);
}
Otherwise if you'd like to check both '' empty string and ' ' with space, you can do that by just adding trim(), something like the code below:
String.prototype.isEmpty = String.prototype.isEmpty || function() {
return !(!!this.trim().length);
}
and you can call it this way:
''.isEmpty(); //return true
'alireza'.isEmpty(); //return false
3 Comments
!(!!this.length) rather than just !this (or !this.trim() for the second option)? A zero-length string is falsy already, the parentheses are redundant, and negating it three times is exactly the same as negating it once.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.
var getLastChar = function (str) {
if (str.length > 0)
return str.charAt(str.length - 1)
}
getLastChar('hello')
=> "o"
getLastChar([0,1,2,3])
=> TypeError: Object [object Array] has no method 'charAt'
So, I'd stick with
if (myVar === '')
...
1 Comment
You can able to validate following ways and understand the difference.
var j = undefined;
console.log((typeof j == 'undefined') ? "true":"false");
var j = null;
console.log((j == null) ? "true":"false");
var j = "";
console.log((!j) ? "true":"false");
var j = "Hi";
console.log((!j) ? "true":"false");
Comments
You should always check for the type too, since JavaScript is a duck typed language, so you may not know when and how the data changed in the middle of the process. So, here's the better solution:
let undefinedStr;
if (!undefinedStr) {
console.log("String is undefined");
}
let emptyStr = "";
if (!emptyStr) {
console.log("String is empty");
}
let nullStr = null;
if (!nullStr) {
console.log("String is null");
}
1 Comment
undefined. This answer is not checking for type.Try this code:
function isEmpty(strValue)
{
// Test whether strValue is empty
if (!strValue || strValue.trim() === "" ||
(strValue.trim()).length === 0) {
// Do something
}
}
1 Comment
(strValue.trim()).length === 0) at the end of the condition? Isn't it redundant with strValue.trim() === ""?I prefer to use not blank test instead of blank
function isNotBlank(str) {
return (str && /^\s*$/.test(str));
}
3 Comments
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.
Comments
The Underscore.js JavaScript library, http://underscorejs.org/, provides a very useful _.isEmpty() function for checking for empty strings and other empty objects.
Reference: http://underscorejs.org/#isEmpty
isEmpty
_.isEmpty(object)
Returns true if an enumerable object contains no values (no enumerable own-properties). For strings and array-like objects _.isEmpty checks if the length property is 0.
_.isEmpty([1, 2, 3]);
=> false
_.isEmpty({});
=> true
Other very useful Underscore.js functions include:
- http://underscorejs.org/#isNull
_.isNull(object) - http://underscorejs.org/#isUndefined
_.isUndefined(value)- http://underscorejs.org/#has
_.has(object, key)
Comments
The following regular expression is another solution, that can be used for null, empty or undefined string.
(/(null|undefined|^$)/).test(null)
I added this solution, because it can be extended further to check empty or some value like as follow. The following regular expression is checking either string can be empty null undefined or it has integers only.
(/(null|undefined|^$|^\d+$)/).test()
1 Comment
(/(null|undefined|^$)/).test("null")This is a falsy value.
The first solution:
const str = "";
return str || "Hello"
The second solution:
const str = "";
return (!!str) || "Hello"; // !!str is Boolean
The third solution:
const str = "";
return (+str) || "Hello"; // !!str is Boolean
1 Comment
NaN which is also falsy.The ultimate and shortest variant of the isBlank function:
/**
* Will return:
* False for: for all strings with chars
* True for: false, null, undefined, 0, 0.0, "", " ".
*
* @param str
* @returns {boolean}
*/
function isBlank(str){
return (!!!str || /^\s*$/.test(str));
}
// tests
console.log("isBlank TRUE variants:");
console.log(isBlank(false));
console.log(isBlank(undefined));
console.log(isBlank(null));
console.log(isBlank(0));
console.log(isBlank(0.0));
console.log(isBlank(""));
console.log(isBlank(" "));
console.log("isBlank FALSE variants:");
console.log(isBlank("0"));
console.log(isBlank("0.0"));
console.log(isBlank(" 0"));
console.log(isBlank("0 "));
console.log(isBlank("Test string"));
console.log(isBlank("true"));
console.log(isBlank("false"));
console.log(isBlank("null"));
console.log(isBlank("undefined"));
Comments
It's a good idea too to check that you are not trying to pass an undefined term.
function TestMe() {
if((typeof str != 'undefined') && str) {
alert(str);
}
};
TestMe();
var str = 'hello';
TestMe();
I usually run into the case where I want to do something when a string attribute for an object instance is not empty. Which is fine, except that attribute is not always present.
Comments
Using core (read vanilla) javascript we can leverage Object.is() for strict equality comparison. Following is a code snippet.
function validateString(arg) {
if (Object.is(arg, "") || Object.is(arg, null) || Object.is(arg, undefined)) {
return false;
}
return true;
}
Here is the JavaScript spec: https://262.ecma-international.org/12.0/#sec-object.is
Here is the Mozilla Doc: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is
Hope this helps.
Comments
An alternative way, but I believe bdukes's answer is best.
var myString = 'hello';
if(myString.charAt(0)){
alert('no empty');
}
alert('empty');
Comments
function isNull(input) {
return input == null;
}
function isEmpty(input) {
return (!input && input !== 0) || input.length === 0 || (Object.getPrototypeOf(input) === Object.prototype && Object.getOwnPropertyNames(input).length === 0);
}
function isBlank(input) {
return isNull(input) || isEmpty(input);
}
function isPresent(input) {
return !isBlank(input);
}
isPresent(undefined) === false &&
isPresent(null) === false &&
isPresent("") === false &&
isPresent([]) === false &&
isPresent({}) === false &&
isPresent(0) === true &&
isPresent(1) === true &&
isPresent("Hello") === true &&
isPresent([1, 2, 3]) === true &&
isPresent({ name: "John" }) === true
// => true
PS: You can copy past this code into your browser console to verify
Comments
complete example. use Object.keys() for types string,array, and object
function isEmpty(input){
switch(typeof input){
case 'undefined': return true
case 'string':
case 'object':
return Object.keys(input).length == 0
case 'boolean':
case 'bigint':
case 'number': return input == 0
}
}
function log(...logs){
for(let i = 0;i < logs.length;i++){
if(i % 2 == 1){
console.log(logs[i - 1],'=', logs[i])
}
}
}
log(
isEmpty(), 'empty undefined', // true
isEmpty(''), 'empty string', // true
isEmpty('abc'), 'empty string', // false
isEmpty([]), 'empty array', // true
isEmpty([2,3]), 'empty array', // false
isEmpty({}), 'empty object', // true
isEmpty({a: 'abc'}), 'empty object', // false
isEmpty(false), 'empty boolean', // true
isEmpty(true), 'empty boolean', // false
isEmpty(0n), 'empty bigint', // true
isEmpty(2n), 'empty bigint', // false
isEmpty(0), 'empty number', // true
isEmpty(2), 'empty number' // false
)
Comments
Here are some custom functions I use for handling this. Along with examples of how the code runs.
const v1 = 0
const v2 = '4'
const v2e = undefined
const v2e2 = null
const v3 = [1, 2, 3, 4]
const v3e = []
const v4 = true
const v4e = false
const v5 = {
test: 'value'
}
const v5e = {}
const v6 = 'NotEmpty'
const v6e = ''
function isNumeric(n) {
return !isNaN(parseFloat(n)) && isFinite(n)
}
function isEmpty(v, zeroIsEmpty = false) {
/**
* When doing a typeof check, null will always return "object" so we filter that out first
* @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/typeof#typeof_null
*/
if (v === null) {
return true
}
if (v === true) {
return false
}
if (typeof v === 'object') {
return !Object.keys(v).length
}
if (isNumeric(v)) {
return zeroIsEmpty ? parseFloat(v) === 0 : false
}
return !v || !v.length || v.length < 1
}
console.log(isEmpty(v1), isEmpty(v1, true))
console.log(isEmpty(v2), isEmpty(v2e), isEmpty(v2e))
console.log(isEmpty(v3), isEmpty(v3e))
console.log(isEmpty(v4), isEmpty(v4e))
console.log(isEmpty(v5), isEmpty(v5e))
console.log(isEmpty(v6), isEmpty(v6e))
Also for reference, here's the source for Lodash isEmpty:
Comments
Well, the simplest function to check this is...
const checkEmpty = string => (string.trim() === "") || !string.trim();
Usage:
checkEmpty(""); // returns true.
checkEmpty("mystr"); // returns false.
It's that dead simple. :)
2 Comments
" "To check if it is empty:
var str = "Hello World!";
if(str === ''){alert("THE string str is EMPTY");}
To check if it is of type string:
var str = "Hello World!";
if(typeof(str) === 'string'){alert("This is a String");}
2 Comments
length is not null. str = ''; str.length == 0 not str.length == null. But on the whole your approach is ok.
nullorundefinedempty? An empty string is an empty string, it is notnullorundefined