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

Embed the value of an array in HTML

Upon running console.log, the data output appears as follows: {TotalPendingResponseCount: 0, TotalRequestSendCount: 1, TotalRequestReceivedCount: 1, TotalRequestRejectCount: 3} To store this information, I am holding it in an array: userData : arrayResp ...

What is the process for applying a border to the chosen image within the ImageList of the MaterialUI component?

Currently, I have set up the images in a grid format using the and components from MaterialUI. However, I am looking to implement an additional feature where when a user clicks on a specific image from the grid, a border is displayed around that select ...

Combining two objects by id and grouping identical key-value pairs together

var routePlan = [ { "id" : 1, "farmerName" : "Farmer1", "farmerId" : 1 }, { "id" : 2, "farmerName" : "Farmer2", "farmerId" : 2 }, { "id" : 1, "farmerName" : "Farm ...

Is there a way to match a compressed javascript stack trace with a source map to pinpoint the correct error message?

When managing our production server, I have implemented minified javascript without including a map file to prevent users from easily deciphering errors. To handle angular exceptions caught by $exceptionHandler, I developed a logging service that forwards ...

Modify a necessary input value using jQuery or JavaScript

I am looking to update the required value of an input based on a checkbox selection. Here is my current code, any assistance would be appreciated. <input type="checkbox" id="no_land_line" name="no_land_line" value=""> // check this box if no land li ...

Utilizing conditional types for type narrowing within a function's body: A comprehensive guide

I created a conditional type in my code that constrains the second argument of my class constructor based on the type of the first argument. Although the type checker correctly limits what I can pass to the constructor, I am struggling to get the compiler ...

jQuery - Show or hide content with a toggle action

Is there a way to toggle the text on a button once certain content is visible? Can the content be hidden if the button is clicked again? To better illustrate, check out this example: JSFiddle I am looking to switch the button text from 'View content ...

Tips for highlighting HTML syntax within JavaScript strings in Sublime Text

Is there a Sublime package available for syntax highlighting HTML within JavaScript strings specifically? (Please note that the inquiry pertains to highlighting HTML within JS strings only, not general syntax highlighting.) Currently, I am developing Ang ...

Steps for changing a component's properties when the component serves as a property

The scenario I'm facing involves a component that receives a prop named button. This button prop is essentially a Component itself, containing various other props within it. My goal is to override the specific prop called type within this nested struc ...

The attempt to decode the string from POST using json_decode failed due to a hang-up in

I'm currently learning about PHP, JSON, and JavaScript. I am facing an issue with using the json_decode function in PHP after receiving a JSON string from JavaScript. I am able to save the JSON string to a file without any problem, but when I try to ...

Show JSON response using AJAX jQuery

After receiving the JSON Response, { "user_data": { "id": 22, "first_name": xxx, "last_name": xxx, "phone_number": "123456789", }, "question_with_answers" : [ { "id": 1, ...

JSX conditionally rendering with an inline question: <option disabled value="">Select an option</option>

Yes, I can confirm that the inline is functioning properly because in the Convert HK to Passive Segment paragraph at the top I am seeing the expected output. What I am aiming for is to display a "Choose a hotel" message when there are multiple hotels in th ...

Is it possible to apply CSS based on a component's displayName?

Are you a CSS pro? I'm attempting to apply a class that will make all descendants of an element read-only, but for some reason the style isn't being applied as expected: #ComponentDisplayName * { -webkit-user-select: text; -moz-user-sel ...

Unlimited scrolling feature in Ionic using JSON endpoint

Trying to create an Ionic list using data from a JSON URL. JSON Code: [{"id":"1","firstName":"John", "lastName":"Doe"}, {"id":"2","firstName":"Anna", "lastName":"Smith"}, {"id":"3","firstName":"Peter", "lastName":"Jones"},{......................}] app.j ...

The issue code R10, indicating a boot timeout, has arisen as the web process failed to connect to $PORT within 60 seconds of initiating on Heroku platform

After deploying my Node.js WebApp to Heroku, I encountered the following error: 2021-06-01T09:19:42.615419+00:00 heroku[web.1]: State changed from crashed to starting 2021-06-01T09:19:47.259832+00:00 heroku[web.1]: Starting process with command `node app.j ...

`html2canvas encountered an issue: Unable to locate a logger instance`

When I use html2canvas to render the same content repeatedly, I encounter an error about 5% of the time. It seems to be sporadic and I'm not sure why it occurs. What could be causing this unpredictable behavior? html2canvas.js:2396 Uncaught (in promi ...

The ajax success() function is failing to function properly when attempting to make a call

The button's onClick() event is not navigating anywhere. There seems to be an issue with the success() function of the ajax call. Unfortunately, I am new to this and unable to pinpoint the problem. var currentAuthor=""; var currentQuote=""; $(documen ...

Having trouble displaying an array in Handlebars on a Node.js and Express server?

I am facing a challenge with handlebars that has me feeling stuck. This is my second day attempting to solve it, but I seem to be hitting a roadblock. My goal is to incorporate handlebars for the first time in order to add some dynamism to the web page I ...

Analyzing file data while uploading the file

Does anyone have a solution for extracting the content from an uploaded file in express/nodejs without saving it as a temporary file? I have code that successfully pipes the input to a filestream, but I'm struggling to deserialize the upload to a pla ...

The JSON array provides the ideal syntax for looping purposes

I am working with JSON data and trying to check if a hovered element matches the names 'sports' or 'technology'. If there is a match, I want to retrieve the corresponding 'text' and 'image' values. However, I am only ...