我想知道是否有可能从Regexp获得无法匹配的结果并将此值放在数组中(只是一个反向匹配)。
此代码部分使用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>"]
预期结果:
[&#34; Lorem ipsum dolor是amet&#34;,&#34;结束&#34;]
答案 0 :(得分:0)
正如评论中提到的,您可以使用拆分。这是工作代码:
"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));
&#13;
当然,在没有多个单独匹配的更一般情况下,这不起作用。你需要更精细的东西。
然后你可以尝试这样的事情:
"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);
&#13;