场景:在富文本编辑器中要求粘贴进来的某些标签不能包含任何属性,只保留标签和内容。
源代码
<span class="code-block-extension-codeLine" data-line-num="14">
pdfjs.
<span class="hljs-property">GlobalWorkerOptions</span>.
<span class="hljs-property">workerSrc</span>
= pdfjsWorker
</span>
目标代码(去掉了标签中所有的属性)
<span>
pdfjs.
<span>GlobalWorkerOptions</span>.
<span>workerSrc</span>
= pdfjsWorker
</span>
转换方法:将html转换为字符串后,用正则表达式过滤,再转换为html
1.str = dom.outerHTML
2.正则处理str
3.dom.outerHTML = str
正则表达式
.replace(/<span(.*?)>/g, `<span$1>`)
如果要替换标签,则采用如下方法
.replace(/<span(.*?)>/g, `<text$1>`).replace(/<\/span>/g, '</text>')
<text>
pdfjs.
<text>GlobalWorkerOptions</text>.
<text>workerSrc</text>
= pdfjsWorker
</text>