I searched for how to exclude empty spaces like " " or " " or " " from an if statments but i didnt find any relevant topic
i have an html page which add a value to an array everytime the user types in a value inside the input field
but i want to exclude the spaces, for example if the user enter only empty spaces, i dont want them to be pushed inside the values[] array
this is my jscode :
const values = []
const inputEL = document.getElementById("field-input")
if (inputEL.value){
values.push(inputEL.value)
inputEL.value = ""
}
I tried this but it didn’t work as expected, user still can enter empty spaces and they are pushed inside the array:
if (!inputEL.value || inputEL.value === " "){
console.log("field input is empty / user enter empty spaces")
else{
values.push(inputEL.value)
inputEL.value = ""
}
>Solution :
You could use trim() to remove whitespaces from the beginnen and end of the string.
So if the input is " ", you well trim() it down to "" which is a falsy value in your if:
const values = []
const inputEL = document.getElementById("field-input");
const trimmed = inputEl.value.trim();
if (trimmed){
values.push(trimmed)
inputEL.value = ""
}