Some conditions are only applied to variables if they hold a proper value. Suppose you are filling out a form and leaving blank spaces. The system will throw a validation error or handle the empty or blank space string. There are many different ways to handle such situations in JavaScript. Let’s focus on the most how to handle nulls and whitespaces using String functions in JavaScript.
We can also handle nulls and whitespaces in a single line using string functions in JavaScript.
String Functions
trim()
method
The trim()
function, when applied to a string and that string is checked against an empty string does the task. Consider the code snippet below.
function checkEmpty(str) {
if (str.trim() === '') {
console.log('String is empty');
} else {
console.log('String is NOT empty');
}
}
const str_a = 'not empty';
const str_b = ''; // empty
const str_c = ' '; // contains only whitespace
checkEmpty(str_a); // outputs: String is NOT empty
checkEmpty(str_b); // outputs: String is empty
checkEmpty(str_c); // outputs: String is empty
The checkEmpty()
function can be applied on different string inputs. It gives the corresponding outputs as shown above. Note that str_c
contains only whitespace, but after being passed to the checkEmpty
function, it consoles ‘String is empty’. This is because of the trim() function, that removes all whitespaces from a string variable.
length() method
We can also use the length function on a string. The function gives length of a string and can therefore help us determine if the string is empty or hold a value. Consider the code sample below.
function checkEmpty(str) {
if (str.length === 0) {
console.log('String is empty');
} else {
console.log('String is NOT empty');
}
}
const str_a = 'not empty';
const str_b = ''; // empty
checkEmpty(str_a); // outputs: String is NOT empty
checkEmpty(str_b); // outputs: String is empty
We can check for strings that contain whitespace using this approach, we can also call the trim()
method before comparing the length of the trimmed string with 0
.
We can further modify this function to check for whitespaces also, as shown in the code below.
function checkEmpty(str) {
if (str.trim().length === 0) {
console.log('String is empty');
} else {
console.log('String is NOT empty');
}
}
const str_a = 'not empty';
const str_b = ''; // empty
const str_c = ' '; // contains only whitespace
checkEmpty(str_a); // outputs: String is NOT empty
checkEmpty(str_b); // outputs: String is empty
checkEmpty(str_c); // outputs: String is empty
Learn how to handle nulls and whitespaces in a single line without String functions.