0

I want to know if is possible get the unmatched result from a Regexp and put this values in array (just an inversing match).

This code handle the solution partially with replace:

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);

//Lorem ipsum dolor is amet  the end

console.log(text);
//["<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"]

jsFiddle

Tabares
  • 4,083
  • 5
  • 40
  • 47

1 Answers1

0

As has been mentioned in comments you can use split. Here's the working code:

"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));

Of course, this doesn't work in the more general situation where you have multiple separate matches. You will need something a bit more elaborate for that.

Then you might try something like this:

"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);
rasmeister
  • 1,986
  • 1
  • 13
  • 19