简体   繁体   English

用单引号引起来的正则表达式不起作用

[英]Regex not working when wrapped in single quotes

I need to wrap a regex in quotes so that I can add another javascript variable into it, but this stops it from working. 我需要将正则表达式用引号引起来,以便可以向其中添加另一个javascript变量,但这会使其停止工作。

Here's the working example... 这是工作示例...

var re = new RegExp(/^(0?[1-9]|[12][0-9]|3[01])[\/\-](0?[1-9]|1[012])[\/\-]\d{4}$/);

And what I eventually want to achieve will look something like this (but amended so that it works): 我最终想要实现的目标将类似于以下内容(但经过修改以使其起作用):

var re = new RegExp('^'+element.defaultValue+'|(0?[1-9]|[12][0-9]|3[01])[\/\-](0?[1-9]|1[012])[\/\-]\d{4}$');

This allows a date formatted DD/MM/YYYY or the default value of the input field. 这允许日期格式为DD / MM / YYYY或输入字段的默认值。

Inside a string literal you need to escape all of the backslashes. 在字符串文字中,您需要转义所有反斜杠。 For example '\\d' is actually just the string 'd' because the Javascript parser takes the backslash as the start of a string escape sequence. 例如, '\\d'实际上只是字符串'd'因为Javascript解析器将反斜杠作为字符串转义序列的开始。 The RegExp() constructor needs actual backslashes in the string so you have to escape them: RegExp()构造函数在字符串中需要实际的反斜杠,因此您必须对它们进行转义:

 `'|(0?[1-9]|[12][0-9]|3[01])[\\/\\-](0?[1-9]|1[012])[\\/\\-]\\d{4}$'`

If the default value you are trying to put into the string contains any special characters you must escape them also. 如果您尝试放入字符串的默认值包含任何特殊字符,则还必须对它们进行转义。 Either escape them in the element.defaultValue or use the answer from this question . 要么将它们转义为element.defaultValue要么使用此问题的答案。

你需要没有逃脱斜线,但转义反斜线:

new RegExp('^'+element.defaultValue+'|(0?[1-9]|[12][0-9]|3[01])[/\\\\-](0?[1-9]|1[012])[/\\\\-]\\\\d{4}$');

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

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