I need to wrap a regex in quotes so that I can add another javascript variable into it, but this stops it from working.
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.
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. TheRegExp()constructor needs actual backslashes in the string so you have to escape them: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.defaultValueor use the answer from this question.