Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to minify HTML block in JavaScript / jQuery?

I have HTML coming from templates that I need to remove spaces between elements and new lines. I don't want to remove spaces that would break the HTML, so it is becoming tricky for me. So far I have the below to remove new lines, but spaces I am stuck on:

'<div id="head"></div> \n   <div id="body"></div>    <div id="foot"></div> '.replace(/(\r\n|\n|\r)/gm, '');

Is there hopefully something built into jQuery instead of a complex regex maybe to remove the spaces?

like image 819
TruMan1 Avatar asked Dec 07 '25 02:12

TruMan1


1 Answers

This should work :

.replace(/^\s+|\r\n|\n|\r|(>)\s+(<)|\s+$/gm, '$1$2')

Fiddle

like image 70
Karl-André Gagnon Avatar answered Dec 08 '25 15:12

Karl-André Gagnon