I’m doing a small javascript method, which receive a list of point, and I’ve to read those points to create a Polygon in a google map.
I receive those point on the form:
(lat, long), (lat, long),(lat, long)
So I’ve done the following regex:
\(\s*([0-9.-]+)\s*,\s([0-9.-]+)\s*\)
I’ve tested it with RegexPal and the exact data I receive:
(25.774252, -80.190262),(18.466465, -66.118292),(32.321384, -64.75737),(25.774252, -80.190262)
and it works, so why when I’ve this code in my javascript, I receive null in the result?
var polygons="(25.774252, -80.190262),(18.466465, -66.118292),(32.321384, -64.75737),(25.774252, -80.190262)";
var reg = new RegExp("/\(\s*([0-9.-]+)\s*,\s([0-9.-]+)\s*\)/g");
var result = polygons.match(reg);
I’ve no javascript error when executing(with debug mode of google chrome). This code is hosted in a javascript function which is in a included JS file. This method is called in the OnLoad method.
I’ve searched a lot, but I can’t find why this isn’t working. Thank you very much!
Use a regex literal [MDN]:
You are making two errors when you use
RegExp[MDN]:/are should not be part of the expressionFurthermore, modifiers are passed as second argument to the function.
So if you wanted to use
RegExp(which you don’t have to in this case), the equivalent would be:(and I think now you see why regex literals are more convenient)
I always find it helpful to copy and past a
RegExpexpression in the console and see its output. Taking your original expression, we get:which means that the expressions tries to match
/,sandgliterally and the parens()are still treated as special characters.Update:
.match()returns an array:which does not seem to be very useful.
You have to use
.exec()[MDN] to extract the numbers:This has to be called repeatedly until the whole strings was processed.
Example:
This creates an array of arrays and the unary plus (
+) will convert the strings into numbers:Of course if you want the values as strings and not as numbers, you can just omit the
+.