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
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
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