Search code examples
javascripthtmlcssregexregexp-replace

How to use regular expressions to match and replace more complex html tag?


How can I use regular expressions to match all tags with a style attribute and a color value, then extract their color value and replace the tag with <color=colorValue>content, please help me, thank you

//original tag
// <p style="color:#ffffff;">content</p>
// <span style="color:#ffffff;">content</span>
// <i style="color:#ffffff;">content</i>
//...


// expect replace tag
//<color=#ffffff>content</color>


Solution

  • const regex = /(?=.*style="color:(#\w+?);")<([a-zA-z]+)[^>]+>(.+?)<\/(\2)>/gm;
    
    const str = `//original tag
    // <p style="color:#ffffff;">content</p>
    // <span style="color:#ffffff;">content</span>
    // <i style="color:#ffffff;">content</i>
    //...
    
    
    // expect replace t
    //<color=#ffffff>content</color>
    `;
    const subst = `<color=$1>$3</color>`;
    
    // The substituted value will be contained in the result variable
    const result = str.replace(regex, subst);
    
    console.log(result);
    
    //output
    //original tag
    // <color=#ffffff>content</color>
    // <color=#ffffff>content</color>
    // <color=#ffffff>content</color>
    
    
    // expect replace t
    //<color=#ffffff>content</color>