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)) {//Find all spans beginning and ending and pushing to array (in the right order)
matches.push({ text: res[0], index: res.index });
}
while(fontSizeMatch = fontSizeRegex.exec(text)) {//looking for style match with regex
toRemove.push({ index: fontSizeMatch.index, length: fontSizeMatch[0].length });//placing strings that we want to remove in the 'toRemove'
count = 0;
for(var i=0; i < matches.length; i++) {//looping all found opening and closing tags
if(matches[i].index <= fontSizeMatch.index)//before the fontsize span or in case it is equal it is the actual font size span
continue;//skip it
if(matches[i].text === "<span")//
count++;
else
count--;
if(count < 0)
break;
}
if(matches[i] === undefined)//not euqal number of opening and closing tags
console.log('bad html!')
if(matches[i].text === "<span") //if found and it is an opening tag we have a problem
console.log('MAJOR PROBLEM')
toRemove.push({ index: matches[i].index, length: matches[i].text.length });//Match! Closing tag, where it starts and length
//while continous since you may find more font size spans
}
toRemove.sort(function(a,b) {//sorting because we want to start removing from the end, since in other case we are goind to break the indexes
if(a.index < b.index)//first is the one with the highest index
return 1;
return -1;
})
console.log(toRemove)
for(var i=0; i<toRemove.length;...