"Do you have a Reg Ex to get rid of whitespace from a web page?" I was asked. "Yes" I replied. Turns out I didn't!

I thought this was possible with a Regular Expression in CF but after having a think, I can't see how. So, the next best thing has to be ColdFusion's List functions surely.

So, to reduce multiple white space characters into one manageable one. Try the following.

Treat the string as a list and change the delimiters to a non-printable character like bell(Chr(7) in ColdFusion). ColdFusion ignores empty list values. Showing this with commars, the following list...

1,2,3,4,5,,,,6

... has six items if we use commar as the delimiter. So when we switch delimiters, all multiples are reduced to one. Here's some sample code

<cfset str = "There's a tab here and five spaces here    .">    <cfset str = ListChangeDelims(str, Chr(7), "  #Chr(10)##Chr(13)#")>    <cfset str = Replace(str, Chr(7), " ", "ALL")>

The third argument to ListChangeDelims() is a string comprised of a space, a tab, carridge return and a line feed. The most likely white space characters to appear in a web page.

I'd be interested to know if there's a better, faster way.