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".

Community
  • 1
  • 1
Stranded Kid
  • 1,395
  • 3
  • 15
  • 23
  • 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` – lxe Nov 06 '14 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. –  Nov 07 '14 at 03:46

1 Answers1

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
lxe
  • 7,051
  • 2
  • 20
  • 32