Regex works in online tester but does not work on my site in javascript

1

Website link where I tested regex

var string = "12.0,34.0";
    var re = new RegExp("[-+]?([1-8]?\d(\.\d+)?|90(\.0+)?),\s*[-+]?(180(\.0+)?|((1[0-7]\d)|([1-9]?\d))(\.\d+))?");
    if (re.test(string)) {
        console.log("Valida");
    } else {
        console.log("Invalida");
    }

Recalling what appears on my console is invalid! I have tested with other simple expressions and it works perfectly the code if someone knows the solution is that I know little or nothing about regex

    
asked by anonymous 01.06.2016 / 11:45

2 answers

1

Take the quotation marks. Try the following:

var string = "12.0,34.0";
var re = new RegExp(/[-+]?([1-8]?\d(\.\d+)?|90(\.0+)?),\s*[-+]?(180(\.0+)?|((1[0-7]\d)|([1-9]?\d))(\.\d+))?/);
if (re.test(string)) {
  console.log("Valida");
} else {
  console.log("Invalida");
}

I tested now, and gave as valid

    
01.06.2016 / 11:56
1

Since the string you have is already formatted and you just need to know if it's valid or not, the best way is not RegExp but a numeric check. Given that the limits are:

Latitude (S-N):   -90 to  +90  
Longitude (O-E): -180 to +180

You can do this:

function verificador(str) {
    var coords = str.split(',').map(Number);
    var validos = coords.filter(function(coord, i) {
        return Math.abs(coord) <= 90 + (90 * i);
    });
    return validos.length == 2 ? coords : false;
};

console.log(verificador("30.02")); // false
console.log(verificador("30.02,-100.876")); // [30.02, -100.876]
console.log(verificador("330.02,-100.876")); // false

jsFiddle: link

    
01.06.2016 / 15:33