Home >Web Front-end >JS Tutorial >Why Is My JavaScript Regex Failing to Extract Coordinates from a String?
Why Isn't This JavaScript Regex Working?
Trying to extract points from a string with a regular expression, a user encountered a null result. The provided regex, "(s([0-9.-] )s,s([0-9.-] )s*)", matches points enclosed in parentheses and separated by commas. However, when applied to a string like "(25.774252, -80.190262),(18.466465, -66.118292),(32.321384, -64.75737),(25.774252, -80.190262)", it fails.
Resolution
The root cause is the incorrect use of RegExp constructor. To use a regex literal, which is more convenient and less error-prone, replace "new RegExp" with "/". Furthermore, modifiers are passed as the second argument:
var reg = /\(\s*([0-9.-]+)\s*,\s([0-9.-]+)\s*\)/g;
Note on Output
match() returns an array of matching strings, which may not be useful for extracting numerical values. Instead, exec() should be used to extract individual matches:
var result, points = []; while ((result = reg.exec(polygons)) !== null) { points.push([+result[1], +result[2]]); }
This will create an array containing coordinates as numbers. Alternatively, if strings are preferred, omit the unary plus ( ).
The above is the detailed content of Why Is My JavaScript Regex Failing to Extract Coordinates from a String?. For more information, please follow other related articles on the PHP Chinese website!