ColdFusion AutoLeadIn UDF

Use this function to pull the first n words from a string.

The incoming string is treated as a space-delimited array. Now we have an array with a word stored in each element. We can output it easily with an index loop, which we set to stop at the count value.

<cfscript>
function autoLeadIn(string,count)
{
// define the return variable
output = '';
if(Trim(string) NEQ '')
{
textarray = ListToArray(string, ' ');

// if the textarray has less items than the count reset the count
if(ArrayLen(textarray) LTE count)
count = ArrayLen(textarray);

// loop for the length of the count param
for(i=1; i LTE count; i=i+1)
{
// append each word to the return variable
output = output & textarray[i];

// if not at end, add a space to the return variable
if(i neq count)
output = output & ' ';

} // close loop
} // end if
return output;
} // end autoLeadIn
</cfscript>

Considerations

If you're pulling a large chunk of text from a database, consider trimming it in your query before passing it to the function to increase performance.

Posted by nagrom on 02/18/2008 at 4:56 PM | Categories: Code -

Comments