React Check if String is Empty
Sometimes, you may need to validate the input values of a string variable and make sure that it is not empty or null. This can be useful for preventing errors, handling edge cases, or implementing conditional logic. In this tutorial, we will give you three examples of how to check if a string is empty or null by using plain JavaScript, React, and Vue. We will also explain the differences and similarities between these frameworks and how they handle empty or null strings.




Thanks for your feedback!
Your contributions will help us to improve service.
How to Check String is Empty or Not in Javascript?
In this example, we use JavaScript to check string is empty or null using !str || str.trim().length === 0;. This expression evaluates to true if the string is empty or null, and false otherwise. You can check and edit this code with tryit
Javascript check if string is empty
xxxxxxxxxx
<script>
const string = ' ';
function isEmpty(str) {
return !str || str.trim().length === 0;
}
function checkString() {
var result = isEmpty(string);
if (result) {
document.getElementById("output").innerHTML = "String is Empty";
} else {
document.getElementById("output").innerHTML = "Sting has some Value";
}
}
</script>
Output of Js Check if string is empty
Example 2 : React check if string is null or empty
In this second example of this tutorial, we use React JS to check if a string is empty or null using a simple condition. The condition is !str || str.trim() === "", which means that the string is either falsy (such as null, undefined, or an empty string) or it has only whitespace characters. This condition can be useful when we want to validate user input or display a default value if the string is empty or null.
React Js Check String is Empty | null | undefined - Javascript Example
xxxxxxxxxx
<script type="text/babel">
const App = () => {
const str = " ";
let message;
if (!str || str.trim() === "") {
message = "String is empty";
} else {
message = "String has some Value ";
}
return (
<div className='container'>
<h1>React Js Check String is empty</h1>
<h3>{message}</h3>
</div>
);
};
ReactDOM.render(<App />, document.getElementById("app"));
</script>
Output of React Js Check String is Empty
Example 3 : vue js check if string is empty
In this third example of this tutorial, we use Vue.js programming language to check if a string is empty or null, undefined using `str && str.trim() !== ""`. This is a common task when we want to validate user input or filter out empty strings from an array.
Vue Js Check String is Empty | null | undefined
xxxxxxxxxx
<script type="module">
const app = new Vue({
el: "#app",
data() {
return {
inputValue: "",
result: "",
};
},
methods: {
checkString() {
const str = this.inputValue;
if (str && str.trim() !== "") {
this.result = "Input Field is Not Empty";
} else {
this.result = "Input Field is Empty";
}
},
},
});
</script>