JSFiddle - React, Tailwind, and code Playground
by George Y
JavaScript
var text = 'Hello <span style="color: #333">world</span><span style="font-size: 13px">Yo man<span style="whatever">mpla mpla mpla</span>should remove after this</span><span style="font-size: 13px">sample text to remove span wrap</span><span style="font-size: 123px">nested after this<span style="font-size: 9px">i am now <span style="color: #333;">in</span> nested</span></span>';
var fontSizeRegex = /(<span [^>]*font-size[^>]*>)/gi;
var spansRegex = /(<\/span>)|(<span)/gi
var matches = [];
var toRemove = [];
var res, count, fontSizeMatch;
while (res = spansRegex.exec(text)) {
matches.push({ text: res[0], index: res.index });
}
while(fontSizeMatch = fontSizeRegex.exec(text)) {
toRemove.push({ index: fontSizeMatch.index, length: fontSizeMatch[0].length });
count = 0;
for(var i=0; i < matches.length; i++) {
if(matches[i].index <= fontSizeMatch.index)
continue;
if(matches[i].text === "<span")
count++;
else
count--;
if(count < 0)
break;
}
if(matches[i] === undefined)
console.log('bad html!')
if(matches[i].text === "<span")
console.log('MAJOR PROBLEM')
toRemove.push({ index: matches[i].index, length: matches[i].text.length });
}
toRemove.sort(function(a,b) {
if(a.index < b.index)
return 1;
return -1;
})
console.log(toRemove)
for(var i=0; i<toRemove.length; i++) {
text = text.substring(0, toRemove[i].index) + text.substring(toRemove[i].index + toRemove[i].length)
}
console.log(text)