Steps to obtain the index of a regex match for every occurrence

I have a string

CO12dadaCO2dafdCO345daaf

I need to retrieve all instances of CO followed by numbers /CO(\d*)([\s\S]*)/, until the next CO appears.

In this scenario, I expect the following output:

['CO12dada', 'CO2dafd', 'CO345daaf']

The regex pattern I attempted also captures all subsequent CO occurrences at once, rendering it ineffective.

While str.search helps locate the index of the first match with a regex, I require the indexes for every instance found.

Answer №1

let inputString = 'CO12dadaCO2dafdCO345daaf';
let regexResult = inputString.match(/(CO.*?)(?=CO|$)/g);
console.log(regexResult);

Answer №2

Use the .split() method to extract your matches:

console.log("CO12dadaCO2dafdCO345daaf".split(/(?!^)(?=CO)/))

Output:

[
  "CO12dada",
  "CO2dafd",
  "CO345daaf"
]

(?!^)(?=CO) = locates the empty string before the substring CO, except at the beginning of the string.

Answer №3

What about this:

DOG\w+?(?=DOG|$)

Check out the demo here: https://regex101.com/r/hJKabc/1

In essence: a "non-greedy" matching of all "word characters" after "DOG" followed by a lookahead for another "DOG" or end-of-string.

If you also wish to include "non-word characters," you can adjust the regex to

DOG[\w\W]+?(?=DOG|$)

This modification will even work on something like

"DOG12barkDOG2woof,barkDOG345tailwag"
and provide matches like:
["DOG12bark", "DOG2woof,bark", "DOG345tailwag"]
.

Answer №4

With the power of JavaScript, you have the ability to utilize

CO[^]*?(?=CO|$)
  • CO[^]*? Find CO, followed by any character including newlines as few times as possible
  • (?=CO|$) Positive lookahead, ensuring that either CO or the end of the line follows

Explore the regex demo here

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

Optimizing Angular for requireJS deletion

We recently developed an Angular directive that utilizes blueimp-fileupload. Everything seems to be working fine until we decided to optimize our code using requireJs. After running the optimizer, we encountered the following error: Error: cannot call m ...

Steps for generating a unique division element for every javascript response

How can I dynamically create a new div for each response in JavaScript? The message is in JSON format containing all the messages sent and received. This is my JavaScript code: $.get("MessageServlet", function (responseJson) { $.each(responseJ ...

Creating an installation package for an Electron application on Windows

Is it possible to create a Mac installer for an Electron app using a Windows PC? I have tried running npm make, but it only generates a Windows installer. ...

The markers are refusing to appear on the map, despite the fact that the data is successfully being retrieved from

<?php error_reporting(E_ALL ^ E_DEPRECATED); $conn = mysql_connect("localhost", "root", "root") or die(mysql_error()); mysql_select_db("db_jawandsons") or die(mysql_error()); ?> <html> <head> <meta http ...

What is the best way to align my clip-path's text with the center of the viewport and ensure that all of the clip-path's text is visible?

Check out my React component demo: https://codesandbox.io/s/epic-brown-osiq1. I am currently utilizing the values of viewBox, getBBox, and getBoundingClientRect() to perform calculations for positioning elements. At the moment, I have hardcoded some values ...

Using Node.js to dynamically load HTML content

I'm just starting out with NodeJs. I'm currently trying to retrieve some HTML from a website to parse it and extract information for debugging purposes. I've had success using the http module (refer to this post), but when I print the ch ...

Is there a way to determine my position in the cycle of WebGL/THREE radians that range from 0 to 1.57, then back to 0, and down to -1.57?

Hey, I've noticed that the radians seem to fluctuate when looking at a camera and trying to animate a flyover. I'm getting repetitive numbers when the camera rotates more than 90 degrees on either side. What could I be overlooking? function calc ...

Encountering issues with loading JavaScript file in Reactjs

I'm currently working with Reactjs (Nextjs) and I am in the process of integrating the home page (index.js). I have various JavaScript files located in the "public" folder and I'm unsure of where to place them. Should I include these files in "_a ...

Error: Unable to establish connection to server with docker-compose due to MongoError

Below is the contents of my docker-compose.yaml file: version: '3' services: app: image: chaseloyd/portfolio-site:latest ports: - "3000:3000" mongo2: image: mongo container_name: mongo2 restart: always ...

JavaScript and JSON interchangeably, the first AJAX response should be rewritten by the second response

I am facing an issue with my code: I have two ajax calls being made on window.load, and it seems like the response from the second AJAX call is overwriting the response from the first one before my function can process it. I'm not sure where I'm ...

What is the process for importing css and js files in laravel-webpack when utilizing a newly installed package through composer?

I've been working on installing this package called phackage. You can find more information about it here. After successfully installing it with Composer PHP, I've encountered several errors because I'm using Laravel 5.4 with Webpack 2 and ...

Having trouble with Vue's $route.push method not working when invoked from a method?

I am currently in the process of creating a search bar for my application using the vue-bootstrap-typeahead autocomplete library. For those unfamiliar, when an option is selected from the suggestions list, it triggers the @hit event which passes the result ...

Is it possible to modify the contents within the JSP div tag without replacing them through an AJAX call?

In my JSP, I face a scenario where there is a div tag with scriptlet content that pulls data from the database every time a request is received from the server. Previously, I was refreshing the entire page with each update, which not only loaded all the re ...

Modify an HTML table and record any modifications as POST requests using Javascript

As a beginner in JavaScript and HTML, I am open to corrections if I am not following the correct practices. Recently, I delved into editing an HTML form table. {%extends 'base.html'%} {%block content%} <html> <body> <h4> Search ...

When attempting to browse for image files, Postman fails to display images

While trying to upload image files through Postman, I encountered an issue where the browser did not display any image files. It's important to note that I am using Ubuntu as my operating system. https://i.sstatic.net/1D3ro.png When I clicked on "se ...

Struggling to integrate data retrieved from a Vue.js API

Once I receive the API call with an attached string input, I successfully get the result. However, I am struggling to incorporate it into my frontend. I have attempted various solutions found online without success and cannot seem to grasp the concept. Her ...

Create a page turning effect in React that simulates scrolling a certain amount at a time

Is there a way to disable default scrolling and have the page automatically scroll to the next item? For example, if I have element2 below element1, how can I set it up so that when I scroll down once, the page scrolls directly to the position of element2 ...

Oh no! "The accuracy of your BMI calculation is in question."

I am currently working on a technical assessment for a BMI calculator, but I am facing a challenge in implementing the formula. The instructions for calculating BMI are as follows: Step 1: The user's height is given in feet, so it needs to be conver ...

"Are you familiar with delving into the intricacies of this

I've managed to implement a directive that changes a HTML class element when you scroll past a certain point on the page. However, the code is a bit of a mystery to me as I pieced it together from various online sources. I really want to understand ho ...

The characteristics that define an object as a writable stream in nodejs

Lately, I've been delving into the world of express and mongoose with nodejs. Interestingly, I have stumbled upon some functionality that seems to work in unexpected ways. In my exploration, I noticed that when I create an aggregation query in mongoos ...