Home > Web Front-end > JS Tutorial > Why Is My JavaScript Regex Failing to Extract Coordinates from a String?

Why Is My JavaScript Regex Failing to Extract Coordinates from a String?

Linda Hamilton
Release: 2024-12-21 17:46:16
Original
249 people have browsed it

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;
Copy after login

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]]);
}
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template