Sign in
Log inSign up
How To Fix White Space Or Empty Strings Entries In JavaScript Using .trim()

How To Fix White Space Or Empty Strings Entries In JavaScript Using .trim()

Egwuda Iko Remi's photo
Egwuda Iko Remi
·May 3, 2022·

2 min read

So you know those times you want certain conditions to be fulfilled before a code can run- conditional statements like:

const yourName = prompt();

if (yourName === “John” ) {
  console.log(yourName);
}
else{
  console.log(“error!”)
}

The user won’t be confronted with any issue whatsoever in situations where s/he entered John(without spacing) as value for the prompt.

In certain situations where the user inputs John(with white spaces) as value for the prompt, the else part of the code will run and print error in the console.

To fix this issue, JavaScript has a built-in function that erases white space and this is the trim() function. What this does is simply to remove white spaces before and after an input and input values with spaces will be treated as if there’s no white spaces. So from the example above:

const yourName = prompt();

if (yourName === “John” ) {
  console.log(“Worked”);
}
else{
  console.log(“error!”)
}

if the developer adds the .trim() function to the variableyourName to look this way:

const yourName = prompt();

if (yourName.trim() === “John” ) {
  console.log(“Worked”);
}
else{
  console.log(“error!”)
}

John(with white space) the first condition will run and Worked will be printed in the console.

Conclusively, In situations where the .trim() is not the code will not throw an error message and this will make the finding the solution process hectic. This is basic but very vital.

Hassle-free blogging platform that developers and teams love.
  • Docs by Hashnode
    New
  • Blogs
  • AI Markdown Editor
  • GraphQL APIs
  • Open source Starter-kit

© Hashnode 2024 — LinearBytes Inc.

Privacy PolicyTermsCode of Conduct