Regarding a Cold Fusion function to do this, Regex can actually make very simple work of this (I'm not saying it's the approach you need to take here, but there may be cases where it's a usueful approach. I use it in image generation.
<cfscript>
function RELeft(string rstring,numeric num,numeric mnum = 0) {
if (len(arguments.rstring) lte num) {
return rstring;
} else {
var match = ReMatch("^(.{#arguments.mnum#,#arguments.num#}(?=\s|$)|.{#arguments.mnum#,#arguments.num#}(?=\b|))",arguments.rstring);
return match[1];
}
}
</cfscript>
<cfset teststring = "this sentenc!- C.I.A. has more than 15 characters, but I only want the first 15, without breaki/ng at a word." />
<cfoutput>#teststring#<br>Left: #Left(teststring,15)#<br>RELeft: #RELeft(teststring,15)# -<br><br></cfoutput>
<cfset teststring = "Shortness." />
<cfoutput>#teststring#<br>Left: #Left(teststring,15)#<br>RELeft: #RELeft(teststring,15)#<br><br></cfoutput>
<cfset teststring = "a.b.c.d.e.f.g.h.i.j.k.l.m.n" />
<cfoutput>#teststring#<br>Left: #Left(teststring,15)#<br>RELeft: #RELeft(teststring,15,15)#<br><br></cfoutput>
<cfset teststring = "myspacebarcalledinsick" />
<cfoutput>#teststring#<br>Left: #Left(teststring,15)#<br>RELeft: #RELeft(teststring,15,13)#<br><br></cfoutput>
<cfset teststring = "a supercalifragilisticexpialidocious day." />
<cfoutput>#teststring#<br>Left: #Left(teststring,15)#<br>RELeft: #RELeft(teststring,15)#<br><br></cfoutput>
<cfset teststring = "a supercalifragilisticexpialidocious day." />
<cfoutput>#teststring#<br>Left: #Left(teststring,15)#<br>RELeft(min 4): `#RELeft("teststring",15,4)#`<br><br></cfoutput>
In truth, some people might want to do this with \b
(regex word boundary). I choose not to do this because .
is a word boundary and you might get tripped up on an abbreviation like F.B.I.
. My function will only match at a period if it absolutely must, say a string like a.b.c.d.e.f.g.h.i.j.k.m.n.o.p
..
It also offers a third parameter to set a minimum number of characters before finding the first space. You can see the difference in the last two examples.