0

Right now my empty text box showing count 1. see the screenshot below:

enter image description here

I want to show 0 value for empty box. how to do that? here is my code:

export default function TextFrom(props) {
  const handelUpClick = () => {
    let newtext = text.toUpperCase();
    setText(newtext);
  };

  const handelLoClick = () => {
    let newtext = text.toLowerCase();
    setText(newtext);
  };

  const handleOnChange = (event) => {
    setText(event.target.value);
  };

  const [text, setText] = useState("");

  return (
    <>
    ..my html code
     <h1>your text summary</h1>
        <p>
          {text.split(" ").length} words and {text.length} character
       </p>
    <> 
boyenec
  • 1,405
  • 5
  • 29
  • Does this answer your question? [Counting words in string](https://stackoverflow.com/questions/18679576/counting-words-in-string) – silencedogood Feb 16 '22 at 15:12

1 Answers1

1

The problem here is that split returns [""] when called on an empty string, and the length of that array is indeed 1. To counteract this, you can replace the {text.split(" ").length} part of your code with {text.trim() === '' ? 0 : text.split(" ").length} so that the case where the input is only whitespace is taken care of.

Connor Mooneyhan
  • 547
  • 6
  • 17
  • Connor Mooneyhan thanks it worked can you please explain little bit this line of code `text.trim() === '' ? 0` I am new in javascript. – boyenec Feb 16 '22 at 15:20
  • 1
    This is the ternary operator. It's basically a shorthand if/else statement, so it checks to see if the trimmed text is an empty string, and if it is, it outputs 0. If not, it splits the string and counts the words. You can read more about the [ternary operator here](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_Operator). – Connor Mooneyhan Feb 16 '22 at 15:22
  • Thanks for your explanation. what `?` sign mean here? – boyenec Feb 16 '22 at 15:23
  • 1
    This is the ternary operator syntax: `[condition] ? [output if true] : [output if false]`. – Connor Mooneyhan Feb 16 '22 at 15:27