JavaScript Minify HTML Regex

后端 未结 2 388
猫巷女王i
猫巷女王i 2021-01-23 09:29

What would the JavaScript regex be to minify contents of HTML. Note that I only want to remove spaces that are >2 and nothing below.

I also want to replace single quotat

相关标签:
2条回答
  • 2021-01-23 10:26

    In the below example all new lines \r\n or spaces between HTML tags are removed, and on the second phase the content within HTML tags is minified, so extra spaces are eliminated.

    Finally trim() is used to remove spaces before & after the final resulting string.

    // dummy string to minify
    var s = `
    
        <div   value="a"     class="a b"   id="a">
          <div>
            foo   bar  
            <br><br>
            <span>baz</span>   <i>a</i>  
          </div>
        </div>
    `
    
    function minify( s ){
      return s
        .replace(/\>[\r\n ]+\</g, "><")
        .replace(/(<.*?>)|\s+/g, (m, $1) => $1 ? $1 : ' ')
        .trim()
    }
    
    console.log(  minify(s)  )

    The above is also available as a gist in my collection

    0 讨论(0)
  • 2021-01-23 10:28

    var s = `
    
        <div   value="a"     class="a b"   id="a">
          <div>
            foo bar  
            <br><br>
            <span>baz</span>   <i>a</i>  
          </div>
        </div>
    `
    
    console.log(
      s.replace(/\s{2,}/g, ' ').replace(/\'/g, '"')
    )

    should do the job for you

    0 讨论(0)
提交回复
热议问题