Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

how to exlude empty spaces from "if-else" statments – JS

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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 = ""
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading