let str = ' <ul><li><span style="font-size: 0.28rem;">你好</span></li><li><span style="font-size: 0.32rem; color: rgb(243, 156, 18);">你好</span></li></ul><p><strong style="color: rgb(0, 59, 165);"><em><u>和地方大幅度发复旦复华大家好房间都会返回放加肥加大几号放假大黄蜂大航</u></em></strong></p><p><em style="color: rgb(0, 59, 165);"><u>ssfsdfdfdsfsdf</u></em><em style="color: rgb(192, 57, 43);"><u>sdfdf</u></em></p><p><em>分隔符<u>冠福股份</u></em><strong><em><u>地方大幅度发</u></em></strong></p><p><img src="https://pic.shuangdj.com/fdb1bf3f30674dbdb9dd9b8d35733b09.png"></p>'
let reg = {
'strong': /(<strong)(\sstyle="[0-9a-zA-Z:\s(,)]+;">)/gm,
'em': /(<em)(\sstyle="[0-9a-zA-Z:\s(,)]+;">)/gm,
'u': /(<u)(\sstyle="[0-9a-zA-Z:\s(,)]+;">)/gm
}
function replaceTag(str, tagName) {
const endTag = '</' + tagName + '>'
let arr = [] // 保存原字符串中,结束标签的索引值
let result = str.replace(reg[tagName], function ($, $1, $2, startIndex) {
let endIndex = str.indexOf(endTag, startIndex)
arr.push(endIndex)
return '<span' + $2 + $1 + '>'
})
arr.map((item, i) => {
const currIndex = item + (i + 1) * 6 + i * 7 // 增加的<span></span>标签长度
result = result.substring(0, currIndex) + endTag + '</span>' + result.substring(currIndex + endTag.length)
})
return result
}
console.log(replaceTag(replaceTag(replaceTag(str, 'strong'), 'u'), 'em'))
console