-2

Regex: /^[0-9\p{L}.,\s]+$/u

I would like to replace the characters not matching with the regex with "".

Celia
  • 59
  • 6

1 Answers1

1

As I understand, you simply want to drop all chars not matching your regex. So the idea is to invert the class of chars:

/^[0-9\p{L}.,\s]+$/u should become /[^\d\p{L}.,\s]+/gu (I added the ^ after the [ to say "not in this list of chars" and replaced 0-9 by \d for digits. Use the g modifier (=global ) to match multiple times.

Running it: https://regex101.com/r/IQz6K5/1

I'm not sure that ,, . and the space will be enough ponctuation. It would be interesting to have a complete example of what you are trying to achieve. You could use another unicode character class for ponctuation if needed, typically with \p{P}. See more info about unicode classes here: https://www.regular-expressions.info/unicode.html#category

Patrick Janser
  • 3,318
  • 1
  • 16
  • 18
  • Thanks Patrick! It works. I implemented the regex into the onChange of the input tag as: `const onChange = (e) => { const result = e.target.value.replace(regex, ""); setValue(result); };` However a special character e.g. `^` is shown if I type it as the first letter. It will not be shown if only I type it as the second letter or so on. – Celia Sep 08 '22 at 07:44
  • Great it helped you. Well, you could use the *keypress* event and then check `event.key` which contains the character pressed. If it's not allowed then you have to simply do `event.preventDefault()` so that the char doesn't appear. But keep the *change* event listener as the user could still copy-paste a value. – Patrick Janser Sep 08 '22 at 15:44