3

I found this regexp for validating floats. But I cant see how 2-1 will accepted. The below evaluates to true. I can't use parseFloat because I need to be able to accept "," instead of "." also. I wrote re2, same result though.

var re1 = new RegExp("^[-+]?[0-9]*\.?[0-9]+$");
console.log(re1.test("2-1"));

var re2 = new RegExp("^([0-9]+)\.([0-9]+)$");
console.log(re2.test("2-1"));
0

3 Answers 3

3

If you generate the regex using the constructor function, you have to to escape the backslash, i.e. \ becomes \\:

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

Another option is to use the literal syntax which doesn't require escaping:

var re1 = /^[-+]?[0-9]*\.?[0-9]+$/
Sign up to request clarification or add additional context in comments.

Comments

3

Sometimes when you create a regex string, you even have to escape the backslash; this can of course be done with a backslash, so the final regex looks something like "\\.*", etc.

Doing this, I was able to get the correct results, as seen here:

var re1 = new RegExp("^[-+]?[0-9]*\\.?[0-9]+$");
console.log(re1.test("2-1"));

var re2 = new RegExp("^([0-9]+)\\.([0-9]+)$");
console.log(re2.test("2-1"));

console.log(re1.test("2.1"));
console.log(re2.test("2.1"));​

Comments

0

What about replacing a comma (",") with a period (".") and then using parseFloat?

Comments

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.