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 quotation marks ' '
with double " "
This is what I got so far, although I'm guessing there's a more efficient way of doing this:
var findSpaces = content.match(' ') >= 2;
var findQuotes = content.match(" ' ");
content.replace(findSpaces, "" );
content.replace(findQuotes, ' " ' );
No j Query please
var s = ` <div value="a" class="ab" 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
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="ab" 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 agist in my collection
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.