Obtain an array containing both matching and non-matching elements

I'm looking to separate a string into an array made up of consecutive substrings, alternating between matches and non-matches of a specified regular expression.

Here's an example:

[nonmatch, match, nonmatch, match...]

For instance, using the correct regex (the exact expression isn't important for now),

"I [went to the doctor] today to [eat some] food"

could be transformed into:

["I ", "[went to the doctor]", " today to ", "[eat some]", " food"]

I have this requirement because I need to temporarily remove certain parts of a string, perform actions on the remaining text, and then place back the removed sections to reconstruct the original string (by simply joining all elements of the array).

All my searches so far lead me to solutions where individuals either want to eliminate certain portions of the input string (e.g. the [] in the above example) or merge non-matches and matches together, like:

["I ", "[went to the doctor] today to ", "[eat some] food"]

Answer №1

To achieve this, you can utilize the split method along with a regular expression that contains capture groups (designated by parentheses). By doing so, the delimiting part will also be retained in the output array:

var sentence = "I [visited the park] yesterday to [have lunch]"
var output = sentence.split(/(\[.*?\])/);
console.log(output); 

The captured segments will consistently appear at the odd indices within the resultant array.

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

"In OSX, running the command 'npm install -g generator-angular-fullstack' will install the Angular Fullstack

As I attempted to configure the MEAN stack, I needed to install Angular. However, when I used the command "npm install -g generator-angular-fullstack", it resulted in an error message displaying in the terminal window. Please refer to the following image ...

Executing a sequence of two asynchronous calls in a serial manner using the promise API

I recently posted a question on Stack Overflow that was somewhat similar to this, but the current issue requires chaining the requests serially. I have two asynchronous requests where the second request depends on the result of the first request in order t ...

Updating state atoms in Recoil.js externally from components: A comprehensive guide for React users

Being new to Recoil.js, I have set up an atom and selector for the signed-in user in my app: const signedInUserAtom = atom<SignedInUser | null>({ key: 'signedInUserAtom', default: null }) export const signedInUserSelector = selecto ...

Jest and Typescript: A guide to mocking the Date object

Is there a way to mock a date object for all unit test cases in TypeScript? I have tried various JavaScript references, but they are not working due to type errors. Can someone offer a solution to resolve this issue? // Testing sampleMethod() describe(&ap ...

Exploring the functionality of iterating through a JSON array of objects with a foreach loop in both JavaScript and Jade

I have a json array that I am trying to display using foreach loop. However, it takes five iterations to show all the data when I would like it to be displayed in a single iteration. How can I achieve this? Below is the jade file code snippet: each item i ...

Conceal navigation buttons on the first and last pages of the slider

I'm attempting to develop a slider that hides the "previous" button when it is on the first slide and hides the "next" button when it reaches the last slide. The slider will be created using a combination of PHP, forms, and JavaScript. Below is the H ...

Can you explain the concepts of 'theme' and 'classes'?

Currently, I am working on a web application using React. I have chosen to incorporate the latest version of Material-UI for designing the user interface. During this process, I came across the demo examples provided by Material-UI (like ) In each demo ...

Postman is showing an error when making a request using Express.js app.get()

Recently, I started working with Express.js and I am using Postman to test my API. When running the code below, I successfully retrieve all members from the object: // gets all members app.get('/api/members', (req, res) => { res.json(membe ...

Substitute :D facial expressions, apart from those occurring within ":D"

My current variable value is: $txt = ':D :D ":D" :D:D:D:D'; I am looking to use the preg_replace function to replace all occurrences of :D with ^, but not if it is surrounded by double quotes like ":D". ===> The desired output is: '^ ^ ...

Critical bug discovered in fundamental Vue.js component by Internet Explorer

My Vue.js-powered application is performing flawlessly in all web browsers, except for one... Upon attempting to launch it on Internet Explorer, a frustrating error appears: An anticipated identifier in vue.min.js, line 6 character 4872 Locating the spe ...

Setting Up AdminLTE Using Bower

Recently, I decided to incorporate the Admin LTE Template into my Laravel project. I diligently followed the guidelines outlined here As soon as I entered the command: bower install admin-lte The installation process seemed to start, but then the ...

What is the proper way to implement if-else statements in JSX?

Is there a way to implement if else statements in JSX? I am currently using the following code snippet <h2 className='font-bold text-lx'>$ {item?.price == null && item?.type =='Sell' ? 'Please contact agency' : ...

Is there a way to adjust the image opacity of a background using Material UI?

Is there a way to adjust the opacity of a background image using Material UI? I attempted to achieve this by utilizing the makeStyles hook in Material UI. Here is an example of my code: import React from 'react'; import {Box,Typography } from &ap ...

Easy Ways to Retrieve the Current Date and Time

Is there a way to retrieve the current date and time using angularjs I attempted the following method: <b>{{Date.Now}}</b> Unfortunately, this approach did not yield the desired results. Any tips or suggestions would be highly valued. ...

Submitting data from a JavaScript frontend to a PHP backend

I've exhausted all options in attempting to resolve this issue. The javascript code is designed to send a list of product IDs to a PHP page. When products are selected, the submit button should activate the submit function. function submit() { ...

Unlocking Discord Account Information through OAuth2

Currently, I am in the process of developing a moderation bot for Discord. I am working on implementing a paid plan and as part of that, I require users to log in with their Discord account using OAuth2. This allows me to retrieve user data and identify wh ...

What is the process of transforming this jQuery script into AngularJS code?

Currently I am facing a situation where I am utilizing Angular1.x for a project. On a specific subpage, there are small clickable images along with some additional content below these images. The requirement is that only the images should be visible init ...

While attempting to deploy my project on Vercel by pulling in my code from GitHub, I ran into this error

As a self-taught Front End developer diving into building and hosting my first web page using React, I've encountered this warning. Any suggestions on how to resolve it? Cloning gitohub.com/Passion94/React-Apps (Branch: main, Commit: da89a2a) Cloning ...

Using Vue Formulate to effortlessly upload multiple images

One of my projects involves using a Vue Formulate component for uploading multiple images to an Express.js backend. Here is the code snippet for the Vue Formulate component: <FormulateInput type="image" name="property_ ...

Encounter an error when reading a stream with a maximum timeout value set

I have encountered a challenge while trying to read and process large CSV files. Due to a rate limit in processing, I need to introduce a 1-minute delay between each request. Initially, I attempted to use set timeout, but discovered that there is a limitat ...