All strings located between the specified phrases

I am attempting to extract strings that are located between two specific strings, but the output I am getting from using str.match is not what I anticipated:

var text = "first second1 third\nfirst second2 third\nfirst second3 third";
var middles = text.match(/first (.*?) third/g);
console.log(middles);  //this should be ["second1", "second2", "second3"]

However, the actual result looks like this:

["first second1 third", "first second2 third", "first second3 third"]

Is there a different approach I can take to only extract the middle strings for each occurrence?

Answer №1

According to the information provided in the RegExp.prototype.exec() documentation:

If your regular expression includes the "g" flag, you have the ability to use the exec method repeatedly to identify consecutive matches within the same string. In such cases, the search commences at the specific substring of str indicated by the lastIndex property of the regular expression (the test() function will also increment the lastIndex property).

Incorporating this concept into your situation:

var text = "first second1 third\nfirst second2 third\nfirst second3 third";
var middles = [], md, regex = /first (.*?) third/g;

while( md = regex.exec(text) ) { middles.push(md[1]); }

middles // ["second1", "second2", "second3"]

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

Execute javascript whenever the page is being loaded

Within my web application, I've implemented a modal popup with a loading bar to appear during any lengthy commands such as button clicks. While this feature is functioning well, there's an issue with the performance of the in-house web server it& ...

Undefined data is frequently encountered when working with Node.js, Express, and Mongoose

Having a beginner's issue: I'm attempting to use the "cover" property to delete a file associated with that collection, but the problem is that it keeps showing up as "undefined". Has anyone else encountered this problem before? Thank you in adv ...

What strategies can be used to stop elements from reverting to their original state?

Hey there, I'm currently experimenting with animation and trying to create a cool two-step effect: 1. elements falling down and 2. pulsating on click. However, I've run into an issue where after the clicking action, the elements return to their o ...

Is there a way to maintain the second form's state when the page is refreshed using Vue.js?

I have a challenge in creating a web-app with only 2 pages. The first page requires filling out forms across two stages, but I am unable to create separate pages for this purpose. Is there a way to display two forms on one page and remain on the second for ...

Having trouble deploying a Heroku app using Hyper? Here's a step-by-step guide to

After running the following commands: https://i.stack.imgur.com/WZN35.png I encountered the following errors: error: src refspec main does not match any error: failed to push some refs to 'https://git.heroku.com/young-brook-98064.git' Can anyon ...

Show a modal component from another component in Angular 2

As a newcomer to Angular, I'm working on a modal component that changes from hiding to showing when a button with (click) is clicked. The goal is to integrate this modal into my main component, allowing me to display the modal on top of the main conte ...

Having trouble getting the toggle menu to work using Jquery?

I am trying to create a toggle menu using jQuery on this particular page: . The menu is located in the top right corner and I want it to appear when someone clicks on the "Menu ☰" button, and then disappear when clicked again (similar to this website: ). ...

Model in Sequelize does not get updated

I have a basic user model with two simple relationships: export const Password = sequelize.define("password", { hash: { type: DataTypes.STRING, allowNull: false, }, salt: { type: DataTypes.STRING, allow ...

The useEffect() method used without any cleanup function

It is mentioned that, "Every time our component renders, the effect is triggered, resulting in another event listener being added. With repeated clicks and re-renders, numerous event listeners are attached to the DOM! It is crucial to clean up after oursel ...

What methods can be used to test included content in Angular?

When testing an Angular component that includes transclusion slots utilizing <ng-content>, it becomes challenging to verify if the transcluded content is correctly placed within the component. For instance: // base-button.component.ts @Component({ ...

Angucomplete-alt fails to display dropdown menu

On my website, there is a textarea where users need to input the name of a group project. The goal is to implement autocomplete functionality, so as users type in the project name, a dropdown menu will appear with suggestions of existing projects to assist ...

How can you establish an environmental variable in node.js and subsequently utilize it in the terminal?

Is there a way to dynamically set an environmental variable within a Node.js file execution? I am looking for something like this: process.env['VARIABLE'] = 'value'; Currently, I am running the JS file in terminal using a module whe ...

The color of the letters from the user textbox input changes every second

My task is to create a page where the user enters text into a textbox. When the user clicks the enter button, the text appears below the textbox and each letter changes color every second. I am struggling with referencing this jQuery function $(function() ...

Refresh the information displayed in the open Google Maps Infowindow

Experimenting with extracting JSON data from a bus tracker website and integrating it into my own version using Google Maps. Although not as visually appealing, I'm struggling to update an infowindow while it remains open. Despite finding some example ...

Phonegap - Retaining text data in a checklist app beyond app shutdown

This is my first time developing an app with Phonegap. I am looking to create a checklist feature where users can input items into an input field. However, I am struggling with figuring out how to save these items so that they remain in the checklist even ...

What is the process for reporting a security vulnerability in an npm package if you are the maintainer and publisher?

If I discover a security flaw in my published packages, how can I indicate which versions are vulnerable so that users running `npm audit` will be alerted? ...

The functionality of my Javascript code is restricted to a single element within a Python embedded for loop in Django2

My Python for loop is iterating through these HTML template cards, each accompanied by JavaScript. However, I'm encountering an issue where the JavaScript only seems to work on the first element (specifically, it's meant to retrieve the seeked po ...

What is the best way to declare a TypeScript type with a repetitive structure?

My data type is structured in the following format: type Location=`${number},${number};${number},${number};...` I am wondering if there is a utility type similar to Repeat<T> that can simplify this for me. For example, could I achieve the same resul ...

Exploration Pointers for Foursquare Web Users

Why does my search suggestion keep returning '568 broadway' even after I have updated the authentication to my client id and client secret? Currently running on: https://api.foursquare.com/v2/venues/suggestCompletion?ll=40.7,-74&query=fours ...

Changing the background color of a PHP input based on the webpage being viewed - here's how!

I'm in the process of creating a website where each page will have its own unique background color. Additionally, I am using a PHP input for both the header and footer sections, which need to change their background colors based on the specific webpa ...