Skip to main content
Inspiring
March 5, 2025
Answered

Regex for removing whitespace between html tags

  • March 5, 2025
  • 2 replies
  • 604 views
<html>  <div><p> Hi there</p>  </div> </html>

Sample code above has whitespace, which I need to get rid of. I've found various examples used in different code settings and tried plugging them into a CF REReplace() function, but nothing has worked so far.

e.g. something like this in node 

var result = html.replace(/>\s+|\s+</g, function(m) {
    return m.trim();
});

 

Any help greatly appreciated.

 

 

    Correct answer kazu98296633
    var result = html.rereplace("\s*([<|>])\s*", "\1", "all");

    2 replies

    kazu98296633Correct answer
    Participating Frequently
    March 6, 2025
    var result = html.rereplace("\s*([<|>])\s*", "\1", "all");
    BKBK
    Community Expert
    March 6, 2025

    Good find, @kazu98296633 . Your suggestion solves a wider problem of which @paul_8809 's is a part. Namely, it removes any spaces before or after the characters "<" and ">" :

    <cfscript>	
    	html = "<html>  <  div >   <               p > Hi there  < /p >  <  /div > <  /html                         >";
    	htmlSpaceless = html.rereplace("\s*([<|>])\s*", "\1", "all");
    	writeoutput(htmlSpaceless); 
    </cfscript>
    

     

    BKBK
    Community Expert
    March 5, 2025

    You could solve it in a simple way, by using reReplaceNocase() twice. The first call replaces ">\s" with ">", the second replaces "\s<" with "<":

    <cfscript>	
    	html = "<html>  <div><p> Hi there</p>  </div> </html>";
    	htmlSpaceless = html.reReplaceNoCase(">\s",">","all").reReplaceNoCase("\s<","<","all");
    	writeoutput(htmlSpaceless); 
    </cfscript>
    paul_8809Author
    Inspiring
    March 5, 2025

    Yes, that is perfect. Thank you so much!

    BKBK
    Community Expert
    March 5, 2025

    My pleasure, @paul_8809 !