Tips for storing an unmatched result in an array with a Regexp

Is it possible to extract the unmatched results from a Regexp and store them in an array (essentially reversing the match)?

The following code partially addresses this issue using the replace method:

str = 'Lorem ipsum dolor is amet <a id="2" css="sanitizer" href="#modal-collection"  data-toggle="modal" data-target="#ae" data-toggle="modal" data-attr-custom="test">Lorem ipsum </a> the end';

let elementRegexp: RegExp = new RegExp('<([^>]+?)([^>]*?)>(.*?)>', 'g');
let text = str.replace(elementRegexp, '');
let matchElements = str.match(elementRegexp);

console.log(text);

// Output: Lorem ipsum dolor is amet  the end

console.log(text);
// Output: ["<a id="2" css="sanitizer" href="#modal-collection"...=modal" data-attr-custom="test">Lorem ipsum </a>"]

Expected result:

["Lorem ipsum dolor is amet", "the end"]

Check out the jsFiddle example here.

Answer №1

If you're looking to extract specific elements from a string, using the split method can be very helpful. Here's an example of how it can be done:

"use strict";

let str = 'Lorem ipsum dolor is amet <a id="2" css="sanitizer" href="#modal-collection"  data-toggle="modal" data-target="#ae" data-toggle="modal" data-attr-custom="test">Lorem ipsum </a> the end';

let elementRegexp = new RegExp('<([^>]+?)([^>]*?)>(.*?)>','g');
let text = str.replace(elementRegexp, '');
let matchElements = str.match(elementRegexp);

console.log(text);
//Lorem ipsum dolor is amet  the end

console.log(matchElements);
//["<a id="2" css="sanitizer" href="#modal-collection"…="modal" data-attr-custom="test">Lorem ipsum </a>"]

console.log(str.split(matchElements));

However, this approach may not work as expected if there are multiple separate matches in the string. In such cases, a more sophisticated solution is required, like the one shown below:

"use strict";

let str = 'Lorem ipsum <a>another</a> dolor is amet <a id="2" css="sanitizer" href="#modal-collection"  data-toggle="modal" data-target="#ae" data-toggle="modal" data-attr-custom="test">Lorem ipsum </a> the end';

let elementRegexp = new RegExp('<([^>]+?)([^>]*?)>(.*?)>','g');
let text = str.replace(elementRegexp, '');
let matchElements = str.match(elementRegexp);

console.log(text);
console.log(matchElements);

let newStr = str;
matchElements.forEach((match, idx) => {
  if (idx < matchElements.length - 1) {
    newStr = newStr.split(match).join('');
  } else {
    newStr = newStr.split(match);
  }
});
console.log(newStr);

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

Ensuring the correctness of phone numbers by validating them with country codes through the use of

I'm currently working on validating phone numbers using intl-tel-input, following the example provided at Below is the code snippet I've been using: var telInput = $("#phone"), errorMsg = $("#error-msg"), validMsg = $("#valid-msg"); // initial ...

Creating interactive and adaptable maps

Currently, I am working on making a Joomla website responsive. However, I have encountered an issue with the SobiPro Map. The problem arises when displaying a map (background img) and points (a link + img) over it with an absolute position. As a result, wh ...

Rails successfully processed the request with a 200 OK status code, however, the $.ajax() function is triggering the 'error' callback instead of the 'success' callback

In my controller, the ajax request is handled as shown below (simplified): def create ... @answer = Answer.new(video: video_file) if @answer.save render json: @answer.video.url else ... end end This is how I have defined my ajax function: $.aja ...

Empty nested Map in POST request

I am currently working on a springboot application with a React/Typescript frontend. I have defined two interfaces and created an object based on these interfaces. export interface Order { customer_id: number; date: Date; total: number; sp ...

Tips for implementing event.preventDefault() with functions that require arguments

Here is a code snippet that I'm working with: const upListCandy = (candy) => { /* How can I add event.preventDefault() to make it work properly? */ axios.post("example.com", { candyName: candy.name }).then().ca ...

What is the reason for instanceof Map returning false?

Utilizing the Draft.js plugin called Mention. When accessing editorState.content.entityMap.mention, I am able to retrieve the value by: mention.get('address') However, when I attempt to verify if it is a Map using: console.log('mention&a ...

What is the best way to ensure that all the divs within a grid maintain equal size even as the grid layout changes?

I have a grid of divs with dimensions of 960x960 pixels, each block is usually 56px x 56px in size. I want to adjust the size of the divs based on the changing number of rows and columns in the grid. Below is the jQuery code that I am using to dynamicall ...

Ensuring User Authentication in Angular with Firebase: How to Dynamically Hide the Login Link in Navigation Based on User's Login Status

After successfully implementing Angular Firebase email and password registration and login, the next step is to check the user's state in the navigation template. If the user is logged in, I want to hide the login button and register button. I tried s ...

When using the JavaScript .sort() method, any undefined value must always be considered as coming before any other value

I am working on sorting an array of objects based on multiple fields, typically around 3-4 fields. Some values within the objects may be undefined, and I need to ensure that these undefined values are considered as "earlier" in the sorting process, wheth ...

The function of hasClass within an if statement appears to be malfunctioning

I'm struggling to figure out why my .hasClass function is not functioning correctly. I've implemented the Quick Search jQuery plugin, and below is the code I am using: <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.mi ...

What is the best way to incorporate and organize the templateHyper folder within an established web project directory?

Can anyone offer advice on how to properly integrate and organize the 'templateHyper' (Bootstrap template) folder within my web project? I've been developing a project using C#, JavaScript, HTML, and Bootstrap's templateHyper. I'm ...

Is it possible for the $.post function to overwrite variables within the parent function?

Recently, I delved into the world of JavaScript and my understanding is quite limited at this point. So, please bear with me as I learn :-) I am working on a basic booking system that saves dates and user IDs in MySQL. The system checks if a particular da ...

Converting seconds to days, hours, and seconds using Moment.js in a ReactJS and TypeScript environment

I would like to achieve the following: I have a value in seconds. When I pass this value to the moment function, I expect to receive the corresponding values for days, hours, and seconds. I have utilized moment.js and managed to output logs as well, but I ...

Issue encountered with the style parameter in print-js when attempting to print from a Vue.js component

While browsing the print-js documentation, I came across a feature that allows us to pass style as a string to the printJS function. However, when attempting to apply this style, I encountered an error preventing the print action: The error I'm facin ...

Ways to reach component method via router

When making an Ajax request and displaying the data in a table component, I encounter an issue where I need to extract the clicked data for use in another Ajax request within a different component that is called through React-Router. The challenge lies in ...

Creating a function for loading dynamic content in XSLT can be achieved by following these steps

When I call the function collapseandexpand() for static elements only, it does not work. Now, how can I create the same function to handle dynamic content in xslt? Javascript Code: <script language="javascript" type="text/javascript> <xsl:text&g ...

JSPM encountered an issue with installation from GitHub (404 error), but it is able to successfully install packages from npm

I am encountering a frustrating issue with my Package.json file for a GitHub repository in my organization. Attempting to pull it in via jspm is causing errors. { "name": "tf-modernizr", "version": "1.0.0", "description": "", "main": "modernizr.js ...

Is there a way for me to link my script for use in a Detail.cshtml file?

I have added the following script to my _Layout.cshtml shared master view: <script src="@Url.Script("~/Scripts/PromptToSave.js")" type="text/javascript"></script> Is there a way to include this script in a Details or index page that does not ...

How to manually trigger the ajaxLoader feature in Tabulator version 3.5

Currently, I am working with version 3.5 of Tabulator from . When populating the table using an ajax request, a "loading icon" is displayed during the loading process. Prior to executing the ajax request for Tabulator, I perform some preliminary check op ...

developing a do-while loop that terminates upon receiving a designated user input

I am currently working on a project to develop a program that generates receipts for customers. The objective is to prompt users for the item name, price, and quantity, then display the resulting array in an organized format. However, I have hit a roadbloc ...