react typescript: How to use regular expression

Viewed 25

I am trying to use regular expressions for the email chip field. But there is an error "Unnecessary escape character".


  const handlePaste = (evt: any) => {
    evt.preventDefault();

    const paste = evt.clipboardData.getData("text");
    const emails = paste.match(/[\w\d\.-]+@[\w\d\.-]+\.[\w\d\.-]+/g);

    if (emails) {
      const toBeAdded = emails.filter((email: any) => !isInList(email));

      setItem(toBeAdded);
    }
  };

enter image description here

I am a beginner in React TypeScript, so I looked at some documents, but I don't understand the clear idea to fix this error. Please give me a solution to solve this problem.

1 Answers

Replace your regex with below regex

/[\w\d\\.-]+@[\w\d\\.-]+\.[\w\d\\.-]+/g

It is good to store regex in variable and use like below

const handlePaste = (evt: any) => {
    evt.preventDefault();
const emailPattern=/[\w\d\\.-]+@[\w\d\\.-]+\.[\w\d\\.-]+/g;
    const paste = evt.clipboardData.getData("text");
    const emails = paste.match(emailPattern);

    if (emails) {
      const toBeAdded = emails.filter((email: any) => !isInList(email));

      setItem(toBeAdded);
    }
  };
Related