RegExpSafeInput.tsx 1.1 KB

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