JavaScript Minify HTML Regex

后端 未结 2 407
猫巷女王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 = `
    
        
    foo bar

    baz a
    ` function minify( s ){ return s .replace(/\>[\r\n ]+\<") .replace(/(<.*?>)|\s+/g, (m, $1) => $1 ? $1 : ' ') .trim() } console.log( minify(s) )

    The above is also available as a gist in my collection

提交回复
热议问题