. Advertisement .
..3..
. Advertisement .
..4..
Are you working on JavaScript Code? Trying to crack the code to check if a string is empty in JavaScript? Are you a beginner or an intermediate programmer to get through the code? Well, you will get the answer in this tutorial in a simpler way.
JavaScript comprises a variety of coding that always help people who are trying to start learning from scratch as well as programmers to make the website interactive by embedding codes with HTML.
When To Use JavaSript Empty Script?
Before checking if a string is empty or not, it is indispensable to know when to use it. An empty string is useful in two ways; Tables and an HTML list. When you need content for tables or an HTML list, an empty string is used. Check out the code when building a list
var data = ["Alen", "John", "Jake", "Steve", "Mark"];
var list = " ";
for (dat) {
list += "<li>" + dat + "</li>";
}
list = "<ul>" + list + "</ul>";
We have to verify if it has a valid value when a variable becomes a string.
Check If a String is Empty
Now that we know when to use it, it the time to look at the simpler method to check the code to see whether the result is true or false
let emptyStr;
if (!emptyStr) {
// String is empty
}
You have to try this code in Javascript to check if the string is empty or not. If the result is False, it means the string is empty.
Now, check out a few ways to check if a string is empty in JavaScript
Using Length and ! Operator
In this method, you will check if a string is empty or not. In the case of an empty string, the result returns true or else false.
function isEmptyFunction(_string) {
return (!_string || _string.length === 0 );
}
console.log(isEmptyFunction(""))
console.log(isEmptyFunction("Hello Ittutoria.net"))
Output
true
false
Using Length === Operator
It symbolizes equals to sign “===
”. In this function, if blank, the result will be “the string is empty” or else “the string is not empty”
function isEmptyCheck(string1) {
if (string1 === "") {
console.log("The string is empty")
}
else{
console.log("The string isn't empty")
}
}
isEmptyCheck("")
isEmptyCheck("Hello Ittutoria.net")
Output
The string is empty
The string isn't empty
Using Replace
If a string is empty or has just white space, it will print “the string is blank” or else the function will print “the string is not blank”.
function isEmptyCheck(_string)
{
if(_string.replace(/\s/g,"") == ""){
console.log("The string is blank")
}
else{
console.log("The string isn't blank")
}
}
isEmptyCheck("")
isEmptyCheck(" ")
isEmptyCheck("Hello Ittutoria.net")
Output
The string is blank
The string is blank
The string isn't blank
If the passed input argument is not a string, the function will display an error “replace is not a function”
Conclusion
Simplest as well as different ways to check if the string is empty in JavaScript have been discussed. I am wishing you easier, quicker, and more efficient coding!
Leave a comment