Use double escaped slashes:
var re = RegExp('^\\d+(?:\\.\\d{0,1})?$');
And it should work.
In JavaScript, you can use a literal and constructor. In literal notation (see the anubhava clause) you need to add / ... / and then you don't need to hide slashes. When using a RegExp object (constructor), you should avoid backslashes.
The constructor is good when you need to pass variables to your template. In other cases, a literal entry is preferred.
var re = /^\d+(?:\.\d?)?$/;
\d{0,1} matches \d? how ? means 0 or 1, greedy .
See this MDN difference for more details .
Literal notation provides compilation of a regular expression when an expression is evaluated. Use letter notation if the regular expression remains constant. For example, if you use a literal notation to build the regular expression used in the loop, the regular expression will not be recompiled at each iteration.
The regular expression object constructor, for example, the new RegExp ('ab + c'), provides compilation of the runtime expression of the regular expression. Use the constructor function when you know the pattern of the expression will change, or you don't know the pattern and get it from another source, such as user input.
When using the constructor function, normal string escape rules (preceding special characters with \ when included in the string) are necessary.
source share