Reputation: 12998
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.
Upvotes: 0
Views: 220
Reputation: 974
You need to not escape the slash, but do escape the backslash:
new RegExp('^'+element.defaultValue+'|(0?[1-9]|[12][0-9]|3[01])[/\\-](0?[1-9]|1[012])[/\\-]\\d{4}$');
Upvotes: 0
Reputation: 95652
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. The RegExp()
constructor needs actual backslashes in the string so you have to escape them:
`'|(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.
Upvotes: 6