How to minify the body of a HTML page using JavaScript

JavaScriptIn a new project where I´m working I needed a way to “minify” the  content of a HTML page in client side, via JavaScript, I mean, all the HTML code inside the tag <body> </body>.

Note: In my particular scenario, all the HTML pages that I want to minify doesn´t have JavaScript code and all css rules are inline.

I came across the next regular expressions that I used in my final code:

// Merge multiple spaces into one space
var string = string.replace(/\s+/g,’ ‘);

// Remove space between tags
var string = string.replace(/>\s+</g,’><‘);

//Remove all kinds of line breaks.
var string = string.replace(/(\r\n|\n|\r)/gm,””)

My final code looks like:

var wikiPageTemplate = wikiPageTemplate.replace(/(\r\n|\n|\r)/gm,"").replace(/\s+/g,' ').replace(/>\s+<');


Hope you find this information useful!!