Home >Web Front-end >JS Tutorial >Why Isn't My JavaScript Regex Matching Coordinates Correctly?
Why This JavaScript Regex Isn't Working
In the provided JavaScript code, the regex var reg = new RegExp("/(s*([0-9.-] )s*,s([0-9.-] )s*)/g"); fails to match the input string var polygons="(25.774252, -80.190262),(18.466465, -66.118292),(32.321384, -64.75737),(25.774252, -80.190262)";, resulting in a null result.
Incorrect Regex Usage
The error stems from two incorrect usages of the RegExp constructor:
Regex Literal
To avoid these pitfalls, it is recommended to use a regex literal, which is enclosed in forward slashes and escaped according to the regular expression syntax:
var reg = /\(\s*([0-9.-]+)\s*,\s([0-9.-]+)\s*\)/g;
Output Extraction
The polygons.match(reg) syntax used in the code returns an array of matched substrings. However, since the input string only contains a single substring that matches the pattern, the result is a single-element array:
["(25.774252, -80.190262),(18.466465, -66.118292),(32.321384, -64.75737),(25.774252, -80.190262)"]
To extract the individual lat/lon pairs as arrays, the match() method should be replaced with exec():
[total match result, lat1, lon1, lat2, lon2, ..., latn, lonn] = reg.exec(polygons);
This will result in an array containing the overall match and all captured groups, allowing for easy access to the lat/lon pairs.
The above is the detailed content of Why Isn't My JavaScript Regex Matching Coordinates Correctly?. For more information, please follow other related articles on the PHP Chinese website!