1

I'm such a newb in regex, but still...
I based my test on this post.

I have this simple regex :

^-?([1]?[1-7][1-9]|[1]?[1-8][0]|[1-9]?[0-9])\.{1}\d{1,6}

In Debuggex, if I test it with 88.5 for example, it matches.

In my JS file, I have :

var lonRegex = new RegExp("^-?([1-8]?[1-9]|[1-9]0)\.{1}\d{1,6}");
var check = lonRegex.test(88.5); // hardcoded for demo
console.log(check) // output false

I can't guess why it's always returning me false, whatever the value is a number or a string like "88.5".

2
  • This has something to do with how regex parts are escaped when creating a regex object from a string. /^-?([1-8]?[1-9]|[1-9]0)\.{1}\d{1,6}/.test(88.5) will return true Commented Nov 6, 2014 at 23:34
  • 1
    Don't construct a regexp from a string, just use a regex literal (/.../). Also, don't check numbers with a regexp, just check them with arithmetic. Commented Nov 7, 2014 at 3:46

1 Answer 1

1

You will need to escape some characters when creating a RegExp object from a string. From MDN:

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

In your case, this will work (note the double \ for \d and .):

var lonRegex = new RegExp("^-?([1-8]?[1-9]|[1-9]0)\\.{1}\\d{1,6}");
var check = lonRegex.test(88.5); // hardcoded for demo
console.log(check) // output true
Sign up to request clarification or add additional context in comments.

2 Comments

Equivalently, you could use var lonRegex = /^-?([1-8]?[1-9]|[1-9]0)\.{1}\d{1,6}/;.
Also, it gives the wrong results for (for example) 0.5 and 90.5.

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.