首頁  >  問答  >  主體

保留包含特定單字的內容,取代除此之外的所有內容的JavaScript正規表示式

我想這很簡單,但我正在努力應對以下情況:

字串(HTML 作為文字傳遞):

text<br>text<br><ul><li>text</li></ul><br>

現在我需要將每個 text<br> 替換為 <div>text</div> 除非文字位於 <li>/<ul> 內。

.replace(/(.*?)<br>/g, '<div></div>')

這工作正常,但如何防止 <ul><li>text</li></ul><br> 被替換?

P粉463824410P粉463824410187 天前393

全部回覆(2)我來回復

  • P粉488464731

    P粉4884647312024-04-02 10:29:52

    "您無法使用正規表示式解析[HTML]。[...]您是否嘗試過使用[HT]ML而是解析器?

    (可以在下面的程式碼片段中找到更簡潔的版本)

    function replaceTextBrWithDiv(html) {
      // Create an element that acts as a parser
      const parser = document.createElement('div');
      parser.innerHTML = html;
    
      // Modify an array-like when iterating over it may cause some issues.
      // Copy it first.
      const childNodes = [...parser.childNodes];
    
      // Index-based iterating
      for (let index = 0; index < childNodes.length; index++) {
        const node = childNodes[index];
        const nextNode = childNodes[index + 1];
    
        if (node instanceof Text && nextNode instanceof HTMLBRElement) {
          const div = document.createElement('div');
    
          // Remove text node from parser and append it to div
          div.appendChild(node);
          nextNode.replaceWith(div);
    
          // Skip next node (i.e. 
    ) index++; } } return parser.innerHTML; }

    嘗試一下:

    console.config({ maximize: true });
    
    function replaceTextBrWithDiv(html) {
      const parser = document.createElement('div');
      parser.innerHTML = html;
    
      parser.childNodes.forEach((node, index, nodes) => {
        const nextNode = nodes[index + 1];
        
        if (node instanceof Text && nextNode instanceof HTMLBRElement) {
          const div = document.createElement('div');
          div.appendChild(node);
          nextNode.replaceWith(div);
        }
      });
      
      return parser.innerHTML;
    }
    
    const content = 'text
    text
    • text

    '; console.log(replaceTextBrWithDiv(content));
    sssccc

    回覆
    0
  • P粉336536706

    P粉3365367062024-04-02 09:47:45

    這是我在尋求(更短的)正規表示式解決方案之前的嘗試:

    const dFrag = document.createDocumentFragment();
    str.textContent.split('
    ').forEach(substr => { const div = document.createElement('div'); let ul; if (!substr) { substr = '
    '; } div.innerHTML = substr; ul = div.querySelector('ul'); if (ul) { dFrag.appendChild(ul); } else { dFrag.appendChild(div); } }); str.innerHTML = ''; str.appendChild(dFrag);

    回覆
    0
  • 取消回覆