简体   繁体   English

反应 typescript:如何使用正则表达式

[英]react typescript: How to use regular expression

I am trying to use regular expressions for the email chip field.我正在尝试对 email 芯片字段使用正则表达式。 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);
    }
  };

在此处输入图像描述

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.我是 React TypeScript 的初学者,所以我查看了一些文档,但我不明白解决此错误的明确想法。 Please give me a solution to solve this problem.请给我一个解决这个问题的方法。

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);
    }
  };

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM