RegExpSafeInput.tsx 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. import React, { ChangeEvent, forwardRef } from 'react';
  2. const specialChars = ['(', '[', '{', '}', ']', ')', '|', '*', '+', '-', '.', '?', '<', '>', '#', '&', '^', '$'];
  3. export const escapeStringForRegex = (event: ChangeEvent<HTMLInputElement>) => {
  4. const value = event.target.value;
  5. if (!value) {
  6. return value;
  7. }
  8. const newValue = specialChars.reduce(
  9. (escaped, currentChar) => escaped.replace(currentChar, '\\' + currentChar),
  10. value
  11. );
  12. return newValue;
  13. };
  14. export const unEscapeStringFromRegex = (value: string) => {
  15. if (!value) {
  16. return value;
  17. }
  18. const newValue = specialChars.reduce(
  19. (escaped, currentChar) => escaped.replace('\\' + currentChar, currentChar),
  20. value
  21. );
  22. return newValue;
  23. };
  24. export interface Props {
  25. value: string | undefined;
  26. placeholder?: string;
  27. className?: string;
  28. onChange: (value: string) => void;
  29. }
  30. export const RegExpSafeInput = forwardRef<HTMLInputElement, Props>((props, ref) => (
  31. <input
  32. ref={ref}
  33. type="text"
  34. className={props.className}
  35. value={unEscapeStringFromRegex(props.value)}
  36. onChange={event => props.onChange(escapeStringForRegex(event))}
  37. placeholder={props.placeholder ? props.placeholder : null}
  38. />
  39. ));