Home > Web Front-end > JS Tutorial > Why Is My JavaScript Regex Returning Null When Matching Points?

Why Is My JavaScript Regex Returning Null When Matching Points?

Patricia Arquette
Release: 2024-12-09 14:55:12
Original
762 people have browsed it

Why Is My JavaScript Regex Returning Null When Matching Points?

Why the JavaScript Regex Isn't Working

Problem:

You're encountering a null result when attempting to match a list of points in JavaScript with a regular expression.

Regex Expression:

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

Solution:

  • Use a regex literal:
var reg = /\(\s*([0-9.-]+)\s*,\s([0-9.-]+)\s*\)/g;
Copy after login
  • Errors using RegExp:

    • Delimiters (/) should not be part of the expression.
    • Backslashes should be escaped if the expression is defined as a string.
    • Modifiers should be passed as a second argument to the function.

Note:

While using RegExp is an option, it's often more convenient to use regex literals.

Extracting Values:

  • .match() returns an array of strings, which may not be useful.
  • .exec() can be used to continuously extract numbers until the entire string is processed:
var result, points = [];
while((result = reg.exec(polygons)) !== null) {
    points.push([+result[1], +result[2]]);
}
Copy after login

This creates an array of arrays containing the extracted numbers. The unary plus ( ) converts the strings to numbers.

The above is the detailed content of Why Is My JavaScript Regex Returning Null When Matching Points?. 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