Edward
Edward

Reputation: 105

regular expression does not work with javascript

I have a regular expression that works on regexplib.com when I test it with the .NET engine. It does not find a match with JavaScript. I have also tried JSFiddle with the below code. It does not find a match. It returns null.

var re = RegExp('^\d+(?:\.\d{0,1})?$');
var myString = "123";
alert(myString.match(re));

I am trying to use the below javascript in an aspx web page. It does not find any matches. I am open to ideas.

function ValidateData(ControlObj, ColumnType) {
var re = new RegExp('^\d+(?:\.\d{0,1})?$');

if (!ControlObj.value.match(re)) {

Upvotes: 6

Views: 329

Answers (2)

anubhava
anubhava

Reputation: 785156

Better use regex literal instead of regex object:

var re = /^\d+(?:\.\d?)?$/;
var myString = "123";
alert(myString.match(re));

Unless until you're building a regular expression dynamically there is no need to use RegExp object.

Otherwise RegExp object needs double escaping like:

var re = RegExp('^\\d+(?:\\.\\d?)?$');

Reason for double escaping is that RegExp object takes a string as input and escaping is needed first for string and second for the regex engine.

btw \d{0,1} can be replaced by \d?

Upvotes: 8

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626845

Use double escaped slashes:

var re = RegExp('^\\d+(?:\\.\\d{0,1})?$');

And it should work.

In JavaScript, you can use literal notation and a constructor. In literal notation (see anubhava's suggestion), you need to add / ... / and then you do not need to escape slashes. When using a RegExp object (a constructor), you must escape backslashes.

Constructor is good when you need to pass variables to your pattern. In other cases, a literal notation is preferrable.

var re = /^\d+(?:\.\d?)?$/;

\d{0,1} is the same as \d? as ? means 0 or 1, greedy.

See more about that difference on MDN.

The literal notation provides compilation of the regular expression when the expression is evaluated. Use literal notation when the regular expression will remain constant. For example, if you use literal notation to construct a regular expression used in a loop, the regular expression won't be recompiled on each iteration.

The constructor of the regular expression object, for example, new RegExp('ab+c'), provides runtime compilation of the regular expression. Use the constructor function when you know the regular expression pattern will be changing, or you don't know the pattern and are getting it from another source, such as user input.

When using the constructor function, the normal string escape rules (preceding special characters with \ when included in a string) are necessary.

Upvotes: 3

Related Questions