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

Asked

Viewed 96 times

1

Link to the site where I tested regex

I test on the site and works correctly the goal is to have 2 numbers as coordinates 12.0,34.0 and receive the valid answer but I am receiving in my invalid log.

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");
    }

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

  • The strings you are testing may have junk or only numbers + comma + numbers and what you need is to know if it is a valid coordinate?

  • only numbers with . and a comma the regex was not correct but now I’ve modified it and everything is working fine

2 answers

1


Remove the quotes. 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 Valida

  • It worked very thank you, you can explain to me why my method is wrong ?

  • Honestly never used RegExp so. I’ll run some tests and I’ll let you know if I find anything

  • Actually yours works too, the problem was the quotes. Try it like this: new RegExp(/[-+]?([1-8]?\d(\.\d+)?|90(\.0+)?),\s*[-+]?(180(\.0+)?|((1[0-7]\d)|([1-9]?\d))(\.\d+))?/);

1

Since the string you have is already formatted and you just need to know if it is valid or not, the best way is not Regexp but a numerical check. Considering that the boundaries are:

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

you can do it like 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: https://jsfiddle.net/v0agez4n/

Browser other questions tagged

You are not signed in. Login or sign up in order to post.