简体   繁体   English

正则表达式检查JavaScript中的经/纬度

[英]Regex checking lat/lon in JavaScript

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. Debuggex中 ,例如,如果我用88.5进行测试,则它匹配。

In my JS file, I have : 在我的JS文件中,我有:

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". 无论值是数字还是像“ 88.5”这样的字符串,我都无法猜测为什么总是返回false。

You will need to escape some characters when creating a RegExp object from a string. 从字符串创建RegExp对象时,需要转义一些字符。 From MDN : 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 .): 在您的情况下,这将起作用(注意\\ d和。的双\\):

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM