Heim  >  Fragen und Antworten  >  Hauptteil

Verwenden von JavaScript und regulären Ausdrücken zum Extrahieren von div-Tags, die img-Tags enthalten

Ich habe eine generierte Zeichenfolge wie diese

tesgddedd<br> <div><img style="max-width: 10rem;" src="folder/mypicture.jpg"><div> <br></div></div>

Ich möchte das Div erhalten, das img enthält, und in diesem Div eine CSS-Klasse hinzufügen, um eine neue Zeichenfolge wie diese zu erhalten

tesgddedd<br> <div class="myCssClass"><img style="max-width: 10rem;" src="folder/mypicture.jpg"><div> <br></div></div>

Ich habe diese Methode ausprobiert

let myString = 'tesgddedd<br> <div><img style="max-width: 10rem;" src="folder/mypicture.jpg"><div> <br></div></div>'
console.log('My new String with div class  : ',myString.match(/<div [^>]*img="[^"]*"[^>]*>/gm)[0])

Es funktioniert nicht.

Was soll ich tun?

P粉252116587P粉252116587407 Tage vor685

Antworte allen(1)Ich werde antworten

  • P粉718165540

    P粉7181655402023-09-09 10:02:25

    建议使用HTML解析器而不是正则表达式,并使用.querySelector来获取带有imgdiv

    使用原生浏览器接口DOMParser.parseFromString来解析HTML。

    const generatedHTML = "tesgddedd<br> <div><img style='max-width: 35rem;' src='folder/mypicture.jpg'><div> <br></div></div>";
    
    const parser = new DOMParser();
    const doc = parser.parseFromString(generatedHTML, "text/html");
    
    // 获取包含直接子img的div元素
    // 注意:它也返回其他子元素
    const divWithImg = doc.querySelector("div:has(> img)");
    
    if (divWithImg) {
      // 捕获到带有img的div
      console.log("Before", divWithImg);
      
      // 添加类名
      divWithImg.className = "myCssClass"
      
      // 更新带有类名的div
      console.log("After", divWithImg);
    } else {
      console.log("No match found.");
    }
    

    下面的代码片段是可视化示例

    const generatedHTML = "tesgddedd<br> <div><img style='max-width: 35rem;' src='folder/mypicture.jpg'><div> <br></div></div>";
    
    const parser = new DOMParser();
    const doc = parser.parseFromString(generatedHTML, "text/html");
    
    // 获取包含直接子img的div元素
    // 注意:它也返回其他子元素
    const divWithImg = doc.querySelector("div:has(> img)");
    
    if (divWithImg) {
      // 用于在页面上预览
      const code = document.querySelector("code");
      
      // 捕获到带有img的div
      code.textContent = `
        Before:
        ${divWithImg.outerHTML}
       `;
      console.log("Before", divWithImg);
      
      // 添加类名
      divWithImg.className = "myCssClass"
      
      // 更新带有类名的div
      code.textContent += `
        After:
        ${divWithImg.outerHTML}
       `;
      console.log("After", divWithImg);
    } else {
      console.log("No match found.");
    }
    <pre><code></code></pre>

    Antwort
    0
  • StornierenAntwort