2

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

1
  • Hello, what is this regex for ? Is it to know if a string contains a float ? Commented Jun 22, 2009 at 6:37

1 Answer 1

5

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);
Sign up to request clarification or add additional context in comments.

2 Comments

Of course this is exactly why the second syntax exists. Escaping makes it less readable.
I agree, I use the second version.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.