Home > Web Front-end > JS Tutorial > Why Are My JavaScript Regexes Failing to Extract Coordinates?

Why Are My JavaScript Regexes Failing to Extract Coordinates?

Barbara Streisand
Release: 2024-12-04 19:01:18
Original
954 people have browsed it

Why Are My JavaScript Regexes Failing to Extract Coordinates?

JavaScript Regex Failure Analysis

When encountering null results from JavaScript regexes, it's important to delve into the intricacies behind the expression. Let's examine why a specific regex for extracting coordinates from a comma-separated string yielded no matches:

Regex construction flaws:

The regex in question was defined as:

new RegExp("/\(\s*([0-9.-]+)\s*,\s([0-9.-]+)\s*\)/g")
Copy after login

Instead, a regex literal should have been used:

var reg = /\(\s*([0-9.-]+)\s*,\s([0-9.-]+)\s*\)/g;
Copy after login
  1. Delimiters are not part of the expression and should not be included.
  2. Regex literals are more convenient and help avoid potential backslash issues.

Regex Output Analysis:

To better understand the regex, one can output its pattern using the console:

/(s*([0-9.-]+)s*,s([0-9.-]+)s*)/g
Copy after login

This reveals that the expression will match literals 's', 'g', and parens literally, which is not the intended behavior.

Array Output Considerations:

It's crucial to note that match() returns an array of matches:

["(25.774252, -80.190262)", "(18.466465, -66.118292)", ... ]
Copy after login

To extract the individual numbers, exec() should be used instead:

["(25.774252, -80.190262)", "25.774252", "-80.190262"]
Copy after login

The unary plus operator ( ) can then be used to convert strings to numbers.

Complete Code:

var reg = /\(\s*([0-9.-]+)\s*,\s([0-9.-]+)\s*\)/g;
var result, points = [];

while((result = reg.exec(polygons)) !== null) {
    points.push([+result[1], +result[2]]);
}
Copy after login

This code will create an array of arrays containing the extracted coordinates as numbers.

The above is the detailed content of Why Are My JavaScript Regexes Failing to Extract Coordinates?. 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