How to Trim White Spaces from input in ReactJS?


We will learn to trim white spaces from the input in ReactJS. Sometimes, users add unnecessary space at the start or end of the input by mistake. So, as a developer, we need to check if the input string contains the white space at the start or end.

If we find white spaces in the input, we should trim it; Otherwise, it can cause issues. For example, we need to store the email in the database, and while registering the email, the user has also added the white spaces by mistake, and we stored the email in the database with white spaces. When a user comes to our application again to log in with the same email, it will give a credential not matching error.

So, we need to store data after trimming the white spaces to avoid errors.

Custom Algorithm

In this approach, we will create a custom algorithm using various JavaScript methods to remove the white spaces from the start and end of the string.

Syntax and Algorithm

Users can follow the steps below to create a custom algorithm to trim strings.

Step 1 – Split the string into the array using the white space as a delimiter.

let array = inputString.split(" ");

In the above step, inputString is a string from the users.

Step 2 – Next, remove the white spaces from the front using the while loop and array.shift() method.

while (array[0] == ") {
   array.shift();
}

Step 3 – Now, remove all white spaces from the end of the string using the while loop and array.pop() method.

while (array[array.length - 1] == "") {
   array.pop();
}

Step 4 – In the last step, join the array of words again to make a string.

let string = array.join(" ");

In the above step, the string contains the input string without any single white spaces.

Example

In the example below, we are taking the string input from the users. We are handling the input using the handleInputString() function.

After entering the whole string, when the user presses the submit button, it will execute the handleSubmit() function. In the handleSubmit() function, we have implemented the above algorithm to trim the white spaces from the input string.

Users can observe the input string without any white spaces in the output.

import React, { useState } from "react";
import validator from "validator";

const App = () => {
  const [inputString, setinputString] = useState("");
  const [finalString, setFinalString] = useState("");

  function handleInputString(event) {
    let string = event.target.value;
    setinputString(string);
  }
  function handleSubmit() {
    let array = inputString.split(" ");
    while (array[0] == "") {
      array.shift();
    }

    while (array[array.length - 1] == "") {
      array.pop();
    }
    
    let string = array.join(" ");
    setFinalString(string);
  }
  return (
    <div>
      <h2>
        {" "}
        Trimming the white spaces from the string 
      </h2>
      <p> Enter a string with some white spaces at beginning and end</p>
      <input type = "text" value = {inputString} onChange = {handleInputString} />
      <div > <br/> The final string after trimming white spaces is: {finalString} 
      </div><br/>
      <button onClick = {handleSubmit}>
        Submit
      </button>
    </div>
  );
};

export default App;

Output

Use the trim() method

The trim() method automatically removes the white spaces from the start and end of the string. We can execute the trim() method on any string by taking the string as a reference.

Syntax

Users can follow the syntax below to use the trim() method in ReactJS to remove the white spaces from the string.

let str = string.trim();

In the above syntax, the string is an input string, and str is a string without white spaces, which is returned from the trim() method.

Example

In the example below, we store the input string in the testString variable and the string after removing white spaces in the finalString variable.

In the handleSubmit() function, we used the trim() method with the inputString string to remove white spaces.

import React, { useState } from "react";

const App = () => {
  const [testString, settestString] = useState("");
  const [finalString, setFinalString] = useState("");

  function handletestString(event) {
    let string = event.target.value;
    settestString(string);
  }
  function handleSubmit() {
    let string = testString;
    setFinalString(string.trim());
  }
  return (
    <div>
      <h3>
        {" "}
        Trimming the white spaces from the string using the
        <i> string.trim() method </i>
      </h3>
      <input type = "text" value = {testString} onChange = {handletestString} />
      <div style = {{ color: "grey", fontSize: "1 rem" }}>
        The final string after removing white spaces is {finalString}
      </div>
      <button
        onClick = {handleSubmit}
        style = {{
          backgroundColor: "grey",
          border: "2px dotted blue",
          borderRadius: "10px",
          color: "blue",
          fontSize: "1.3rem",
          padding: "0.5rem",
        }}
      >
        Submit
      </button>
    </div>
  );
};
export default App;

Output

We learned to remove white spaces using the trim() method. Also, we have created custom algorithms to explain to beginners how the trim() method works.

Also, users can use the validator npm package to trim white spaces from the string.

Updated on: 08-Sep-2023

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements