Reputation: 69647
Is there a string.Empty
in JavaScript, or is it just a case of checking for ""
?
Upvotes: 4111
Views: 5755652
Reputation: 3270
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
Upvotes: 2
Reputation: 2146
I use such approach
[null, undefined, ''].includes(value)
Upvotes: 5
Reputation: 341
There is a lot of useful information here, but in my opinion, one of the most important elements was not addressed.
null
, undefined
, and ""
are all falsy.
When evaluating an empty string, it's often because you need to replace it with something else.
In this case, you can expect the following behavior.
var a = ""
var b = null
var c = undefined
console.log(a || "falsy string provided") // prints ->"falsy string provided"
console.log(b || "falsy string provided") // prints ->"falsy string provided"
console.log(c || "falsy string provided") // prints ->"falsy string provided"
With that in mind, a method or function that can return whether or not a string is ""
, null
, or undefined
(an invalid string) versus a valid string is as simple as this:
const validStr = (str) => str ? true : false
validStr(undefined) // returns false
validStr(null) // returns false
validStr("") // returns false
validStr("My String") // returns true
Please note, you probably also want to trim()
the string since "" !== " "
.
Upvotes: 29
Reputation: 1033
check that var a;
exist
trim out the false spaces in the value, then test for emptiness
if ((a)&&(a.trim()!=''))
{
// if variable a is not empty do this
}
Upvotes: 23
Reputation: 2358
if ((input?.trim()?.length || 0) > 0) {
// input must not be any of:
// undefined
// null
// ""
// " " or just whitespace
}
Or in function form:
const isNotNilOrWhitespace = input => (input?.trim()?.length || 0) > 0;
const isNilOrWhitespace = input => (input?.trim()?.length || 0) === 0;
Explanation:
If input
is undefined
or null
then the null coalescing ?.
will result in input?.trim()?.length
will be undefined
or null
. ORing (||
) that with 0
will give 0
. 0
is not > 0
therefore the result will be false
, ie it IS a nil value.
If input
is empty or whitespace then .trim()
will remove leading and ending whitespace, which will keep an empty input the same, and convert any whitespace to an empty value. The length of an empty string is then 0
, and as above, 0
is not > 0
, therefore the result will be false
, ie it IS empty or only whitespace.
If input
is any other string, it's length will be > 0 after calling .trim()
, and therefore the result will be true
, ie it IS NOT a nil value, and it IS NOT empty or only whitespace.
Upvotes: 29
Reputation: 191
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
)
Upvotes: 1
Reputation: 3037
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.
Upvotes: 3
Reputation: 1047
Check if it's type string AND if it's not empty:
const isNonEmptyString = (val) => typeof val === 'string' && !!val
Upvotes: 7
Reputation: 353
You can check this using the typeof operator along with the length method.
const isNonEmptyString = (value) => typeof(value) == 'string' && value.length > 0
Upvotes: 5
Reputation: 169
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"));
Upvotes: 4
Reputation: 1104
Try this code:
function isEmpty(strValue)
{
// Test whether strValue is empty
if (!strValue || strValue.trim() === "" ||
(strValue.trim()).length === 0) {
// Do something
}
}
Upvotes: 5
Reputation: 1280
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
Upvotes: 4
Reputation: 2666
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:
Upvotes: 0
Reputation: 155895
To check for a truthy value:
if (strValue) {
// strValue was non-empty string, true, 42, Infinity, [], ...
}
To check for a falsy value:
if (!strValue) {
// strValue was empty string, false, 0, null, undefined, ...
}
To check for exactly an empty string, compare for strict equality against ""
using the ===
operator:
if (strValue === "") {
// strValue was empty string
}
To check for not an empty string strictly, use the !==
operator:
if (strValue !== "") {
// strValue was not an empty string
}
Upvotes: 5061
Reputation: 14824
For checking if a variable is falsey or if it has length attribute equal to zero (which for a string, means it is empty), I use:
function isEmpty(str) {
return (!str || str.length === 0 );
}
(Note that strings aren't the only variables with a length
attribute, arrays have them as well, for example.)
Alternativaly, you can use the (not so) newly optional chaining and arrow functions to simplify:
const isEmpty = (str) => (!str?.length);
It will check the length, returning undefined
in case of a nullish value, without throwing an error. In the case of an empty value, zero is falsy and the result is still valid.
For checking if a variable is falsey or if the string only contains whitespace or is empty, I use:
function isBlank(str) {
return (!str || /^\s*$/.test(str));
}
If you want, you can monkey-patch the String
prototype like this:
String.prototype.isEmpty = function() {
// This doesn't work the same way as the isEmpty function used
// in the first example, it will return true for strings containing only whitespace
return (this.length === 0 || !this.trim());
};
console.log("example".isEmpty());
Note that monkey-patching built-in types are controversial, as it can break code that depends on the existing structure of built-in types, for whatever reason.
Upvotes: 1441
Reputation: 1325
I use:
function empty(e) {
switch (e) {
case "":
case 0:
case "0":
case null:
case false:
case undefined:
return true;
default:
return false;
}
}
empty(null) // true
empty(0) // true
empty(7) // false
empty("") // true
empty((function() {
return ""
})) // false
Upvotes: 82
Reputation: 5729
All the previous answers are good, but this will be even better. Use dual NOT operators (!!
):
if (!!str) {
// Some code here
}
Or use type casting:
if (Boolean(str)) {
// Code here
}
Both do the same function. Typecast the variable to Boolean, where str
is a variable.
It returns false
for null
, undefined
, 0
, 000
, ""
, false
.
It returns true
for all string values other than the empty string (including strings like "0"
and " "
)
Upvotes: 564
Reputation: 6286
I use a combination, and the fastest checks are first.
function isBlank(pString) {
if (!pString) {
return true;
}
// Checks for a non-white space character
// which I think [citation needed] is faster
// than removing all the whitespace and checking
// against an empty string
return !/[^\s]+/.test(pString);
}
Upvotes: 15
Reputation: 315
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. :)
Upvotes: -2
Reputation: 625
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");}
Upvotes: -11
Reputation: 917
Trimming whitespace with the null-coalescing operator:
if (!str?.trim()) {
// do something...
}
Upvotes: 11
Reputation: 11233
A lot of answers, and a lot of different possibilities!
Without a doubt for quick and simple implementation the winner is: if (!str.length) {...}
However, as many other examples are available. The best functional method to go about this, I would suggest:
function empty(str)
{
if (typeof str == 'undefined' || !str || str.length === 0 || str === "" || !/[^\s]/.test(str) || /^\s*$/.test(str) || str.replace(/\s/g,"") === "")
return true;
else
return false;
}
A bit excessive, I know.
Upvotes: 23
Reputation: 56341
Very generic "All-In-One" Function (not recommended though):
function is_empty(x)
{
return ( //don't put newline after return
(typeof x == 'undefined')
||
(x == null)
||
(x == false) //same as: !x
||
(x.length == 0)
||
(x == 0) // note this line, you might not need this.
||
(x == "")
||
(x.replace(/\s/g,"") == "")
||
(!/[^\s]/.test(x))
||
(/^\s*$/.test(x))
);
}
However, I don't recommend to use that, because your target variable should be of specific type (i.e. string, or numeric, or object?), so apply the checks that are relative to that variable.
Upvotes: 44
Reputation: 2827
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");
}
Upvotes: 5
Reputation: 92347
I perform tests on macOS v10.13.6 (High Sierra) for 18 chosen solutions. Solutions works slightly different (for corner-case input data) which was presented in the snippet below.
Conclusions
!str
,==
,===
and length
are fast for all browsers (A,B,C,G,I,J)test
,replace
) and charAt
are slowest for all browsers (H,L,M,P)In the below snippet I compare results of chosen 18 methods by use different input parameters
""
"a"
" "
- empty string, string with letter and string with space[]
{}
f
- array, object and function0
1
NaN
Infinity
- numberstrue
false
- Booleannull
undefined
Not all tested methods support all input cases.
function A(str) {
let r=1;
if (!str)
r=0;
return r;
}
function B(str) {
let r=1;
if (str == "")
r=0;
return r;
}
function C(str) {
let r=1;
if (str === "")
r=0;
return r;
}
function D(str) {
let r=1;
if(!str || 0 === str.length)
r=0;
return r;
}
function E(str) {
let r=1;
if(!str || /^\s*$/.test(str))
r=0;
return r;
}
function F(str) {
let r=1;
if(!Boolean(str))
r=0;
return r;
}
function G(str) {
let r=1;
if(! ((typeof str != 'undefined') && str) )
r=0;
return r;
}
function H(str) {
let r=1;
if(!/\S/.test(str))
r=0;
return r;
}
function I(str) {
let r=1;
if (!str.length)
r=0;
return r;
}
function J(str) {
let r=1;
if(str.length <= 0)
r=0;
return r;
}
function K(str) {
let r=1;
if(str.length === 0 || !str.trim())
r=0;
return r;
}
function L(str) {
let r=1;
if ( str.replace(/\s/g,"") == "")
r=0;
return r;
}
function M(str) {
let r=1;
if((/^\s*$/).test(str))
r=0;
return r;
}
function N(str) {
let r=1;
if(!str || !str.trim().length)
r=0;
return r;
}
function O(str) {
let r=1;
if(!str || !str.trim())
r=0;
return r;
}
function P(str) {
let r=1;
if(!str.charAt(0))
r=0;
return r;
}
function Q(str) {
let r=1;
if(!str || (str.trim()==''))
r=0;
return r;
}
function R(str) {
let r=1;
if (typeof str == 'undefined' ||
!str ||
str.length === 0 ||
str === "" ||
!/[^\s]/.test(str) ||
/^\s*$/.test(str) ||
str.replace(/\s/g,"") === "")
r=0;
return r;
}
// --- TEST ---
console.log( ' "" "a" " " [] {} 0 1 NaN Infinity f true false null undefined ');
let log1 = (s,f)=> console.log(`${s}: ${f("")} ${f("a")} ${f(" ")} ${f([])} ${f({})} ${f(0)} ${f(1)} ${f(NaN)} ${f(Infinity)} ${f(f)} ${f(true)} ${f(false)} ${f(null)} ${f(undefined)}`);
let log2 = (s,f)=> console.log(`${s}: ${f("")} ${f("a")} ${f(" ")} ${f([])} ${f({})} ${f(0)} ${f(1)} ${f(NaN)} ${f(Infinity)} ${f(f)} ${f(true)} ${f(false)}`);
let log3 = (s,f)=> console.log(`${s}: ${f("")} ${f("a")} ${f(" ")}`);
log1('A', A);
log1('B', B);
log1('C', C);
log1('D', D);
log1('E', E);
log1('F', F);
log1('G', G);
log1('H', H);
log2('I', I);
log2('J', J);
log3('K', K);
log3('L', L);
log3('M', M);
log3('N', N);
log3('O', O);
log3('P', P);
log3('Q', Q);
log3('R', R);
And then for all methods I perform speed test case str = ""
for browsers Chrome v78.0.0, Safari v13.0.4, and Firefox v71.0.0 - you can run tests on your machine here
Upvotes: 75
Reputation: 2665
Starting with:
return (!value || value == undefined || value == "" || value.length == 0);
Looking at the last condition, if value == "", its length must be 0. Therefore drop it:
return (!value || value == undefined || value == "");
But wait! In JavaScript, an empty string is false. Therefore, drop value == "":
return (!value || value == undefined);
And !undefined is true, so that check isn't needed. So we have:
return (!value);
And we don't need parentheses:
return !value
Upvotes: 15
Reputation: 189
I didn't see a good answer here (at least not an answer that fits for me)
So I decided to answer myself:
value === undefined || value === null || value === "";
You need to start checking if it's undefined. Otherwise your method can explode, and then you can check if it equals null or is equal to an empty string.
You cannot have !! or only if(value)
since if you check 0
it's going to give you a false answer (0 is false).
With that said, wrap it up in a method like:
public static isEmpty(value: any): boolean {
return value === undefined || value === null || value === "";
}
PS.: You don't need to check typeof, since it would explode and throw even before it enters the method
Upvotes: 13
Reputation: 261
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()
Upvotes: 4
Reputation: 1423
You can use lodash: _.isEmpty(value).
It covers a lot of cases like {}
, ''
, null
, undefined
, etc.
But it always returns true
for Number
type of JavaScript primitive data types like _.isEmpty(10)
or _.isEmpty(Number.MAX_VALUE)
both returns true
.
Upvotes: 62
Reputation: 4192
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:
_.isNull(object)
_.isUndefined(value)
_.has(object, key)
Upvotes: 4