tags:

views:

48

answers:

1

Dear all,
I wrote a regular expression
^([+/-]?([0-9]+(.)?)|([0-9]*.[0-9]+))$
I create it by two ways

var _regex = "^([+/-]?([0-9]+(\.)?)|([0-9]*\.[0-9]+))$";
var _regexFloat = new RegExp(_regex);

and

var _regexFloat = /^([+/-]?([0-9]+(\.)?)|([0-9]*\.[0-9]+))$/ ;

the testing data is "1a" and "a1".
at the second way, it work fine.
but in the first way, it returns true.

Can anyone suggest me if I have something wrong.

Thanks very much.

Environment:

Windows Server 2003
IE 6

+5  A: 

I believe you'll need to escape those backslashes in the string (in the first version).

Try this:

var _regex = "^([+/-]?([0-9]+(\\.)?)|([0-9]*\\.[0-9]+))$";
var _regexFloat = new RegExp(_regex);
Jeff Meatball Yang
Of course this is exactly why the second syntax exists. Escaping makes it less readable.
Matthew Flaschen
I agree, I use the second version.
Jeff Meatball Yang