表达式作为字符串存储在变量中
expression stored in variable as string
我有这个有效的代码。
myDate = str.match(/(\d{1,4}([.\-/])\d{1,2}([.\-/])\d{1,4})/g);
但是我想将表达式存储为变量并使用它。
像这样:
pattern = "/(\d{1,4}([.\-/])\d{1,2}([.\-/])\d{1,4})/g"; // I understand this is wrong somehow
myDate = str.match(pattern);
如何将我的表达式存储为变量并按照我展示的方式使用它?
提前致谢。
删除引号:
pattern = /(\d{1,4}([.\-/])\d{1,2}([.\-/])\d{1,4})/g;
myDate = "01-01-2021".match(pattern);
console.log(myDate);
好的,在玩了一下之后我通过这样做去掉引号来让它工作。
var pattern=/(\d{1,4}([.\-/])\d{1,2}([.\-/])\d{1,4})/g;
myDate = str.match(pattern);
与 JavaScript 中的大多数内容一样,正则表达式模式是一个对象 - 具体来说,是一个 RegExp 对象。作为 explained in MDN:
There are two ways to create a RegExp object: a literal notation and a constructor.
- The literal notation's parameters are enclosed between slashes and do not use quotation marks.
- The constructor function's parameters are not enclosed between slashes but do use quotation marks.
与您的示例相关的附加点是 g
标志添加在文字符号的末尾,但作为构造函数中的单独参数。因此,以下任一方法都有效:
pattern = /(\d{1,4}([.\-/])\d{1,2}([.\-/])\d{1,4})/g;
pattern = new RegExp('\d{1,4}([.\-/])\d{1,2}([.\-/])\d{1,4})', 'g');
您的尝试没有给出错误,但与字符串不匹配的原因已解释 on the MDN page for the match
function:
If regexp is a non-RegExp object, it is implicitly converted to a RegExp by using new RegExp(regexp).
所以你的代码等同于:
pattern = "/(\d{1,4}([.\-/])\d{1,2}([.\-/])\d{1,4})/g";
myDate = str.match(new RegExp(pattern));
当你想要的是:
pattern = "(\d{1,4}([.\-/])\d{1,2}([.\-/])\d{1,4})";
myDate = str.match(new RegExp(pattern, "g"));
我有这个有效的代码。
myDate = str.match(/(\d{1,4}([.\-/])\d{1,2}([.\-/])\d{1,4})/g);
但是我想将表达式存储为变量并使用它。 像这样:
pattern = "/(\d{1,4}([.\-/])\d{1,2}([.\-/])\d{1,4})/g"; // I understand this is wrong somehow
myDate = str.match(pattern);
如何将我的表达式存储为变量并按照我展示的方式使用它?
提前致谢。
删除引号:
pattern = /(\d{1,4}([.\-/])\d{1,2}([.\-/])\d{1,4})/g;
myDate = "01-01-2021".match(pattern);
console.log(myDate);
好的,在玩了一下之后我通过这样做去掉引号来让它工作。
var pattern=/(\d{1,4}([.\-/])\d{1,2}([.\-/])\d{1,4})/g;
myDate = str.match(pattern);
与 JavaScript 中的大多数内容一样,正则表达式模式是一个对象 - 具体来说,是一个 RegExp 对象。作为 explained in MDN:
There are two ways to create a RegExp object: a literal notation and a constructor.
- The literal notation's parameters are enclosed between slashes and do not use quotation marks.
- The constructor function's parameters are not enclosed between slashes but do use quotation marks.
与您的示例相关的附加点是 g
标志添加在文字符号的末尾,但作为构造函数中的单独参数。因此,以下任一方法都有效:
pattern = /(\d{1,4}([.\-/])\d{1,2}([.\-/])\d{1,4})/g;
pattern = new RegExp('\d{1,4}([.\-/])\d{1,2}([.\-/])\d{1,4})', 'g');
您的尝试没有给出错误,但与字符串不匹配的原因已解释 on the MDN page for the match
function:
If regexp is a non-RegExp object, it is implicitly converted to a RegExp by using new RegExp(regexp).
所以你的代码等同于:
pattern = "/(\d{1,4}([.\-/])\d{1,2}([.\-/])\d{1,4})/g";
myDate = str.match(new RegExp(pattern));
当你想要的是:
pattern = "(\d{1,4}([.\-/])\d{1,2}([.\-/])\d{1,4})";
myDate = str.match(new RegExp(pattern, "g"));