What is the reason behind the array being returned by this regular expression

I recently came across this example from MDN showcasing the use of the string's match method:

var str = "For more information, see Chapter 3.4.5.1";
var re = /(chapter \d+(\.\d)*)/i;
var found = str.match(re);

console.log(found);

// logs ["Chapter 3.4.5.1", "Chapter 3.4.5.1", ".1"]

// The first match is "Chapter 3.4.5.1" and it corresponds to (Chapter \d+(\.\d)*).

// The value ".1" is captured from (\.\d)

I find the results of the RegExp matching in JavaScript a bit confusing. I expected it to return ["Chapter 3.4.5.1", ".4.5.1"]. Can someone clarify why the result is different?

Answer №1

    ["Section 2.5.8.6", "Section 2.5.8.6", ".6"]
      |                        |             |
      |                        |             |
Matched string           Characters inside Characters inside the group index 2. Essentially `*` is performing a greedy match. In this (\.\d)* , it consumes all the `.\d` and captures only the final `.\d` segment because you didn't capture the subsequent `*`.
                          the group index
                             1    

DEMO

In order to achieve the desired result, you must capture the following * in this (\.\d)* pattern and also eliminate the initial capturing group.

DEMO

> var str = "To find out more, refer to Section 2.5.8.6";
undefined
> var re = /section \d+((?:\.\d)*)/i;
undefined
> str.match(re);
[ 'Section 2.5.8.6',
  '.8.6',
  index: 26,
  input: 'To find out more, refer to Section 2.5.8.6' ]

Answer №2

The method str.match() will give you an array containing the overall match along with any matches within parentheses.

In order to achieve the result of ["Chapter 3.4.5.1", ".4.5.1"], your code needs to be structured like this:

var str = "For more information, see Chapter 3.4.5.1";
var re = /chapter \d+([\.\d]*)/i;
var found = str.match(re);

console.log(found);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How can one create a function that delays the execution of code until AJAX data is received

I developed a CKEditor plugin that fetches data via ajax to create RichCombo functionality. The plugin functions correctly, however, when there are multiple instances of the editor on a single page, each plugin ends up sending its own ajax request, leading ...

Retrieve data from a ng-repeat variable within a controller

Below is the current code snippet: HTML <center><li ng-repeat = "x in items | orderBy: 'priority'"> <!-- color code priorities --> <span ng-style="cmplt" ng-class="{ red: x.type == &apo ...

When `rxjs` repeat and async pipe are applied and then removed from the DOM, the resulting value becomes null

One of the classes I have is responsible for managing a timer. It contains an observable that looks like this: merge( this._start$, this._pause$ ) .pipe( switchMap(val => (val ? interval(1000) : EMPTY)), map( ...

``Are you looking to create multiple canvases in a loop?

I've managed to get this command working exactly as I wanted: http://jsfiddle.net/m1erickson/64BHx/ However, I didn't anticipate how challenging it would be to turn the drawing into reality here: What I attempted to do is illustrated in this li ...

Issue with activation of onClick event in case/switch statement

Currently working on a JavaScript project to recreate the Fallout terminal game, with one of the main aspects being comparing words selected by the user to those chosen by the computer. The concept of this hacking game is reminiscent of the board game Mas ...

Moving the input box down to the lower portion of the screen

My goal is to create an interactive input box that glides smoothly to the bottom of the screen when clicked by the user. However, the current implementation causes the input box to move too far down, requiring the user to scroll down in order to see it. H ...

Using ng-transclude directive in AngularJS for input values

My goal is to develop a directive that includes the ng-transclude value in the input field's value attribute within an HTML template: The directive I have created: module.directive('editInput', function(){ return { restrict: &a ...

Trouble with running dynamically injected <SCRIPT> tags in Firefox version 47.0

After making an AJAX call, I receive an HTML snippet that looks like this: <SCRIPT src="..." type="text/javascript"></SCRIPT> <SCRIPT type="text/javascript"> function showForumGrid() { ... }; function f() { ...} </SCRIPT> < ...

Modify the data format displayed in CRUD output to dd/mm/yyyy

Despite the fact that this question has been asked multiple times before, I have tried various solutions and none seem to be working for me. I am trying to modify the output in my CRUD so that the date format changes from yyyy-mm-dd to dd/mm/yyyy. Here is ...

What is the process of invoking a function in Typescript?

I am curious about how to effectively call this function in TypeScript. Can you guide me on the correct way to do it? type Fish = { swim: () => void }; type Bird = { fly: () => void }; function move(animal: Fish | Bird) { if ("swim" in ...

A tip for transferring the value of a binding variable to a method within the template when the button is clicked

I am currently exploring the concept of binding between parent and child components using @Input, @Output, and EventEmitter decorators. This is demonstrated in the HTML snippet below: <h1 appItemDetails [item]="currentItem">{{currentItem}}& ...

Incorporating JSON data on-the-fly into a space tree visualization

I'm currently utilizing spacetree js to display the tree view. My goal is to dynamically load the json data after clicking on a node. I have tried running the sample examples with hardcoded json values. However, I am unsure of how to make it more d ...

Sending a form from an iPhone device to a PHP backend server

It seems like I'm overlooking a simple aspect... Here is a basic form that I want to submit to a PHP script. It works perfectly on PC and Mac, but it doesn't function properly in Safari on iPad, iPhone, etc. Do you think there's some mobile ...

Merge the throw new Error statement with await in a single expression

Is it possible to combine throwing an error and using the await keyword in one statement using the AND operator? The code snippet below demonstrates my intention: throw new Error() && await client.end(). So far, this approach has been working wel ...

Using ES6 to create a callback function that stores values in a Map

I've been trying to find an answer to this question by searching extensively, but haven't had any luck. Currently, I am developing a React app and faced with the task of storing the state, which happens to be a map, in a local variable. Here is ...

Vue's computed property utilizing typed variables

I am trying to create a computed array of type Todo[], but I keep encountering this specific error: No overload matches this call. Overload 1 of 2, '(getter: ComputedGetter<Todo[]>, debugOptions?: DebuggerOptions | undefined): ComputedRef<T ...

What is the method for generating a JSON file similar to this one when I provide input?

How can I align the cart_items to meet my expectations? That's all I want. My only problem is that I just want to make my cart_items look like this. I hope you can help me, thanks. Did I use the wrong method? Also, I want to include the qty inside the ...

Using regular expressions to eliminate text located outside of the tags within a string

Presented is a string consisting of an XML string below: var xmlString = "<str>rvrv</str>rvrv<q1>vrvv</q1>vrvrv<q2>rtvrvr</q2>"; I am seeking assistance on how to eliminate text that lies outside the tags (text no ...

Discover the method of utilizing my current location to determine the distance between two points by inputting their latitude and longitude

I'm currently working on customizing my REST API to only retrieve items that fall within a specific radius. I have successfully written the code to calculate the distance between two points and filter out items outside the desired range. However, my c ...

Expo is having trouble locating the module "color-convert" - such a frustrating problem

Having an issue! I ran the command npm start in my terminal and received the following error: Starting project at /home/pc/Documents/Projects/Mobile/weather_app Developer tools running on http://localhost:19002 Cannot find module 'color-convert' ...