Filter Out Specific Characters in a React Input

Share this video with your friends

Send Tweet

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 /)

Vincent Schoettke
Vincent Schoettke
~ 6 years ago

This has the “usual” problem that the cursor jumps to the end when typing unwanted characters.

Gosha Arinich
Gosha Arinich(instructor)
~ 6 years ago

This has the “usual” problem that the cursor jumps to the end when typing unwanted characters.

True, but I plan to cover how to prevent that in a separate lesson!

Ioannis Cherouvim
Ioannis Cherouvim
~ 6 years ago

That regex will need a "g" at the end in order to replace all "illegal" characters that may appear at once in the input value, e.g via pasting.

Gosha Arinich
Gosha Arinich(instructor)
~ 6 years ago

This has the “usual” problem that the cursor jumps to the end when typing unwanted characters.

For what it's worth, my lesson about that just got published — https://egghead.io/lessons/react-preserve-cursor-position-when-filtering-out-characters-from-a-react-input