Conditions are often applied to variables only if they hold a proper value. Suppose you are filling a form and leave blank space. The system should throw a validation error or handle the empty or blank space string. There are numerous ways to handle such situation in JavaScript. Let’s focus on the most simple way to handle nulls and whitespaces in a single line in JavaScript.
String functions like trim(), empty(),
or length()
can be used to check if a string holds a proper value. A simple and straight forward way to check this without use of functions is to use ""
and validate a string input.
Handle nulls and whitespaces in a single line
You can simply validate a string input using an if
condition, quotation marks, and some operators. Consider the code snippet below.
if((source_name != "") && (source_name != " ")){
console.log("a valid source name is entered");
// do something
}
The if
condition above checks if the string is not empty and has no white spaces, and does the corresponding process accordingly.
Likewise you can just change the operators to ==
instead of !=
and throw an error if string is empty or had whitespace.
if((source_name == "") && (source_name == " ")){
console.log("Error! Please enter a valid source name");
}
The simple method allows us to validate for both empty strings and white spaces in a single line!
There are numerous string methods in JavaScript, but I would always recommend to use this method. As methods may at times be not supported by browsers, but this simple code snippet can be easily implemented and supported by browsers. Moreover, it covers two checks in a single line.
To handle nulls and whitespaces in JavaScript using string functions, refer to String functions to handle nulls and whitespaces.