Utilizing regular expressions in Javascript to retrieve multiple instances

This paragraph contains a specific string

txt = "Local residents o1__have called g__in o22__with reports...";

that requires extracting numbers between each occurrence of o and __

If we use the following regex:

txt.match(/o([0-9]+)__/g);

We will obtain:

["o1__", "o22__"]

However, the desired output is:

["1", "22"]

How can this transformation be achieved?

Answer №1

Take a look at this thread:

content = "The team scored g__23 touchdowns and won o99__games.";
var pattern = /o([0-9]+)__/g
var results = [];
var result = pattern.exec(content);
while (result != null) {
    results.push(result[0]);
    result = pattern.exec(content);
}
console.log(results);

Answer №2

To obtain successive matches, you must utilize the .exec() method on a regular expression object and make sure to use the g flag like in the example below:

var textContent = "The team o3__captain is g__called up to the field o14__at 2pm.";
var regEx = /o([0-9]+)__/g;
var matchResult;
while ((matchResult = regEx.exec(textContent)) !== null) {
    console.log(matchResult[1]);
}

The last index state of the previous match within the regular expression object is saved as lastIndex, which serves as the starting point for the next match.

See it in action here: http://jsfiddle.net/anotherexample123/DmP9Q/

More information about using regular expressions this way can be found here: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/RegExp/exec.

Answer №3

/o([0-9]+?)__/g

Give this a try. Check it out here and look for "lazy star".

var rx = new RegExp( /o([0-9]+?)__/g );
var txt = "Local residents o1__have called g__in o22__with reports...";
var mtc = [];
while( (match = rx.exec( txt )) != null ) {
        alert( match[1] );
        mtc.push(match[1]);
}

Jek-fdrv mentioned in the comments that calling rx.test just before the while loop can skip some results. This is because the RegExp object has a lastIndex field that tracks the index of the last match in the string. When lastIndex changes, the RegExp continues matching from that updated index, causing part of the string to be skipped. Here's a simple example:

var rx = new RegExp( /o([0-9]+?)__/g );
var txt = "Local residents o1__have called g__in o22__with reports...";
var mtc = [];
console.log(rx.test(txt), rx.lastIndex); //outputs "true 20"
console.log(rx.test(txt), rx.lastIndex); //outputs "true 43"
console.log(rx.test(txt), rx.lastIndex); //outputs "false 0" !!!
rx.lastIndex = 0; //manually resetting lastIndex field works in Chrome
//now everything works smoothly
while( (match = rx.exec( txt )) != null ) {
        console.log( match[1] );
        mtc.push(match[1]);
}

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

Using identical content in various template slots

Is it possible in vuejs to assign the same content to multiple slots without repeating it? For example: <base-layout> <template slot="option"> <span :class="'flag-icon-' props.option.toLowerCase()" />{{ countriesByCode ...

Ways to dynamically refresh a Vue component when data is updated without the need to manually reload the

After fetching data using axios, I noticed that my Vue component doesn't update automatically after a click event or when the data changes. As a workaround, I have to refresh the page to see the updated data. Is there a simple solution to this issue? ...

Creating phony passwords effortlessly in JavaScript utilizing the informal library

I am trying to create a password that meets the following criteria: Minimum length: 7 Maximum length: 15 At least one uppercase letter At least one lowercase letter Special characters: ~ ! @ # $ % ^ * ( ) _ + ? I have been using the casual library for g ...

The previous successful execution of req.body is now yielding an undefined value

My req.body is suddenly undefined, even though it was working fine a few days ago. I've tried using the deprecated body-parser module, but no luck. Here's my code: JS: var express = require("express"); var router = express(); require(& ...

WebSocket connection was unsuccessful. Switching to Comet and resending the request

I have been utilizing the Atmosphere framework 2.0.0.RC5 to expand my web application with websocket capabilities and encountered a perplexing error 'Websocket failed. Downgrading to Comet and resending' that I can't seem to resolve. To sta ...

I am currently exploring next.js and working on creating a dedicated single post page within my project

I am currently working with Next.js and fetching some dummy data on the homepage. However, I am facing an issue when trying to create a separate page for each post obtained from the homepage. Although I have already coded it, I feel like there is room fo ...

Issue with React redirect not functioning post transition

A component I created includes a redirection route that triggers after an animation finishes. Here is the code for reference: Menus.jsx class Menus extends Component{ constructor (props) { super(props); this.state = { select: 'esp ...

Replace the value of a variable when another variable becomes false in Angular.js

Currently, I am working on a project using Angular and have run into an issue that I need help with: In my project, I have two variables - signed which is a boolean bound to a checkbox, and grade which is an integer bound to a number input field. I am lo ...

Tips for successfully passing multiple data IDs in a Bootstrap modal

Greetings! I am currently facing a challenge with passing multiple data IDs into a bootstrap modal. When I manually assign the data IDs, everything works perfectly: <a id="testB" href="#my_modal2" data-toggle="modal" data-book-id='{"id":10,"name ...

A sleek Javascript gallery similar to fancybox

I'm currently working on creating my own custom image gallery, inspired by fancybox. To view the progress so far, please visit: I've encountered some issues with the fade effects of #gallery. Sometimes the background (#gallery) fades out before ...

Starting http-server in the background using an npm script

Is there a way to run http-server in the background using an npm script, allowing another npm script, like a Mocha test with jsdom, to make HTTP requests to http-server? To install the http-server package, use: npm install http-server --save-dev In your ...

Filtering server-side components in Next.js to create a customized list

Having been accustomed to the previous architecture of Next.js, I embarked on a new project where I am exploring the use of server and client components in the latest architecture. Specifically, I have a page dedicated to displaying race results in a tabl ...

Switch button displaying stored data in sessionStorage

I am facing an issue with my small toggle button in AngularJS. I have set up sessionStorage to store a value (true or false), and upon page load, I retrieve this value from sessionStorage to display the toggle button accordingly. Depending on the value sto ...

Automatically update div content using AJAX in a different approach

In my situation, I am facing a unique challenge compared to other queries. I have a div element with the following code <div id="ondiv"><?php ?></div> Within this PHP section are details of people who are currently online. Ideally, when ...

The system cannot locate the module: Unable to find '@reactchartjs/react-chart-2.js'

I've been working on implementing this chart using the npm module called react-chartjs-2. I followed these steps to install the module: Ran the command: npm install --save react-chartjs-2 chart.js As a result, my package.json file now looks like th ...

The function does not have a specified return value

I've been grappling with this issue for quite some time and I can't figure out what's causing the problem. In my code, I have a separate class called Database.js that handles MySQL functions, manages connections, queries, etc. My goal is to ...

Controlling international shortcuts for numerous npm packages

Within my root folder, I have 3 npm projects organized in a more complex structure than the following example (using webpack, JS frameworks, etc.), but for simplicity sake, here is the layout: root ├── root_index.js ├── package.json ├── p ...

Display the mobile keyboard without the presence of an input element

Attempting to display the mobile keyboard on my responsive site, I initially tried placing a hidden input with the placeholder "tap here." However, due to an event firing on this input that reloads the dom, I was unable to show the keyboard. I'm wond ...

Guide on populating a Vue.js input field with a value retrieved from a JSON object

Could someone please assist me with a problem I am encountering? I need to extract and display the values from an input form for "name" and "position", but the data is in JSON format. {"id":5,"name":"the name","pos":"the position"} This code snippet repr ...

Attempting to deploy my initial Google Cloud Function, encountering an error message indicating that Express is not detected

Currently in the process of deploying my first Google Cloud function, the code for which can be found here: https://github.com/rldaulton/GCF-Stripe/blob/master/Charge%20Customer/index.js The code starts with the following line: var app = require('e ...