stringLen()

stringLen()

Version: 1.0 build 20040608
Requires: Adobe ColdFusion 5.0 or greater
Total size: 1.44 KB
Download time: 0.26 seconds at 56kbps
Edition: Freeware

Description

This function takes a string and returns its length, measured in your choice of unites, including characters, words, sentences, and paragraphs. You should strip any HTML from the string before measuring it.

Returns

An integer.

Category

String

Parameters


Parameter Type Required? Default Description
str string Yes The string
units string No
  • "paragraphs": Measure the string length in paragraphs
  • "sentences": Measure the string length in sentences
  • "words": Measure the string length in words (default)
  • "characters": Measure the string length in characters

UDF source


 
<cfscript>
  /**
  * Measure the length of a plain text string using a range of different units
  * 
  * @param str              The string (Required)
  * @param units            Units to count: "Characters", "words" (default),
  *                         "sentences", or "paragraphs" (Optional)
  * @return numeric
  * @author Matthew Walker, WWW.eswsoftware.com
  * @version 1, 2004-06-08
  */
  
  function stringLen(str) {
    var result = 0;
    var units = "words";
    
    if ( not structKeyExists(request, "eswsoftware") )
      request.eswsoftware = structNew();
    if ( not structKeyExists(request.eswsoftware, "stringLen") )
      request.eswsoftware.stringLen = structNew();  
    request.eswsoftware.stringLen.version = 1;
	
    if ( arrayLen(arguments) gte 2 )
      units = arguments[2];  
    
    switch(units) {
    
      case "paragraphs": {
        str = reReplace(str, "#chr(10)#[[:space:]]*#chr(10)#", chr(30), "all");
	    result = listLen(str, chr(30));
        break;
      }

      case "sentences": {
        str = reReplace(str, "(\.[[:space:]]*)+", ".", "all");
        result = listLen(str, ".");
        break;
      }
      
      case "characters": {
        result = len(str);
        break;
      }
      
      default: {
        str = reReplace(str, "[[:space:][:punct:]]+", " ", "all");
        result = listLen(str, " ");
      }
    
    }
    
    return result;
  }
</cfscript>
World Wide Web
HyperText Markup Language
The coding language used to create hypertext documents for use on the World Wide Web.