JavaScript 将用户输入的字符串转换为正则表达式
在本文中,我们将使用JavaScript将用户输入的字符串转换为正则表达式。要在JavaScript中将用户输入转换为正则表达式,您可以使用 RegExp构造函数 . RegExp构造函数以字符串作为其参数,并将其转换为正则表达式对象
正则表达式 (RegExp)是用于匹配字符串中的字符组合的模式。在JavaScript中,正则表达式也是对象。在JavaScript中有两种构建正则表达式的方法。
使用正则表达式字面量,它由斜杠之间的模式组成,如下所示。
const reg = /ab+/;
调用RegExp对象的构造函数,如下所示。
const reg = new RegExp('ab+', flag);
使用构造函数提供了正则表达式的运行时编译,因此我们应该在这里使用第二种方法,因为字符串是来自用户的动态输入。上述两个表达式对应同一个正则表达式。
示例 1: 对于字符串,我们将使用“Geeks For Geeks”。
Input : '^Ge'
Output: ["Ge"]
0: "Ge"
Input : '[A-z]+'
Output: (3) ["Geeks", "For", "Geeks"]
0: "Geeks"
1: "For"
2: "Geeks"
const str = "Geeks for Geeks";
// Input from User
const regex = prompt("Enter RegExp");
// Conversion from string to RegExp
const reg = new RegExp(regex, "g");
// The match fn returns the array of strings
// That match to RegExp
const result = str.match(reg);
if (result) console.log(result);
else console.log("Not Found");
输出:
示例2: 在这个示例中,我们将使用 RegExp构造函数 。
const userInput = prompt("Enter a regular expression pattern:");
const regex = new RegExp(userInput);
console.log(regex);
输出: