regex 如何用div标签替换具有特定类名的HTML span开始和结束标签

velaa5lx  于 2023-05-19  发布在  其他
关注(0)|答案(1)|浏览(121)

我有这个HTML代码

<span class="line"><span>// Before</span></span> 
<span class="line">
  <span>import</span>
<span> </span><span>db</span>
<span> </span><span>from</span><span>    </span>
  <span>'../../lib/db-admin'</span><span>;</span>
</span> 
<span class="line"><span>// After</span></span> 
<span class="line"><span>import</span>
<span> </span><span>db</span><span> </span>
<span>from</span><span> </span>
<span>'lib/db-admin'</span><span>;</span></span>

我想用div标签替换class=“line”的每个开始和结束span标签。如何使用正则表达式来实现?
这是我已经尝试过的,但直到工作状态才能得到它。

/(<span class="line">.*?<\/span>)\s*<span class="line">(.*?)<\/span>((?!<\/span>).)*<\/span>/g, '$1</div><div class="line">$2</div>'
mlmc2os5

mlmc2os51#

不要使用正则表达式来分析/解析HTML字符串。使用DOM解析器。您可以使用DOMParser并执行以下操作:

function replaceWithDivs(html, selector) {
    const doc = new DOMParser().parseFromString(html, "text/html");
    for (const elem of doc.querySelectorAll(selector)) {
        const div = doc.createElement("div"); // Create the new element
        div.innerHTML = elem.innerHTML;       // Copy the contents
        elem.replaceWith(div);                // And replace old with new
    }
    return doc.body.innerHTML;
}

// demo
let html = `<span class="line"><span>// Before</span></span> 
<span class="line">
  <span>import</span>
<span> </span><span>db</span>
<span> </span><span>from</span><span>    </span>
  <span>'../../lib/db-admin'</span><span>;</span>
</span> 
<span class="line"><span>// After</span></span> 
<span class="line"><span>import</span>
<span> </span><span>db</span><span> </span>
<span>from</span><span> </span>
<span>'lib/db-admin'</span><span>;</span></span>`;

html = replaceWithDivs(html, "span.line");
console.log(html);

相关问题