Reputation: 1395
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".
Upvotes: 1
Views: 198
Reputation: 7589
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
Upvotes: 1