Join egghead, unlock knowledge.

Want more egghead?

This lesson is for members. Join us? Get access to all 3,000+ tutorials + a community with expert developers around the world.

Unlock This Lesson
1×
Become a member
to unlock all features

Level Up!

Access all courses & lessons on egghead today and lock-in your price for life.

Autoplay

    Filter Out Specific Characters in a React Input

    Gosha ArinichGosha Arinich
    reactReact
    javascriptJavaScript

    Learn to filter out the unwanted characters from your input.

    We will achieve this by running replace on the new input value in the onChange handler, before updating the state.

    Note: you need to be using a version of React that supports Hooks (versions 16.8.0 and higher) to follow this lesson.

    The regexp at 1:07 should be /[^a-zA-Z\s]/g (with g added after the closing /)

    Code

    Code

    Become a Member to view code

    You must be a Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson
    Discuss

    Discuss

    Transcript

    Transcript

    Instructor: We have this simple React application with a name input. The value of that input is stored in the nameState variable, and it's passed down to the input component. The handleNameChange updates the nameState variable.

    We want to prevent the user from typing any character that is not a letter or a space character into the input. We want to filter out all of the numbers and special characters. We don't want to have this as a possible value of the name.

    To achieve that we'll go to the handleNameChange function, and create a new variable here called newName. Its value will be event, target, value. We use this new variable in the setName call, setName(newName).

    To filter out the unwanted characters, we'll call replaceOnValue. We'll give it a regular expression pattern, and we'll replace every character that matches that pattern with an empty string, essentially removing that character.

    We can now see that we can input a normal name value, but if we try to input something like a number or a special character, it's not being added at all, no matter where we try to add it.