CFLib.org – Common Function Library Project

WordInstance(word, string)

Last updated September 20, 2004

author

Joshua Miller

Version: 2 | Requires: CF5 | Library: StrLib

Description:
Returns the number of occurances of a word in a string.

Return Values:
Returns the number of times the word appears.

Example:

<CFSET STR = "The is the way the world ends, not with a bag but with a whimper. The whimper to end all of the other wimpers.">
<CFOUTPUT>#WordInstance("the",str)#</CFOUTPUT>

Parameters:

Name Description Required
word The word to count. Yes
string The string to check. Yes

Full UDF Source:

/**
 * Returns the number of occurances of a word in a string.
 * Minor edit by Raymond Camden
 * 
 * @param word      The word to count. (Required)
 * @param string      The string to check. (Required)
 * @return Returns the number of times the word appears. 
 * @author Joshua Miller (josh@joshuasmiller.com) 
 * @version 2, September 20, 2004 
 */
function WordInstance(word,string){
    var i=0;
    var start=1;
    var j = 1;
    var tmp = "";
    
    string = " " & string & " ";
    for(j=1;j lte Len(string);j=j+1){
        tmp=REFindNoCase("[^a-zA-Z]+#word#[^a-zA-Z]+",string,start);
        if(tmp gt 0){
            i=i+1;
            start=tmp+Len(word);
        }else{
            start=start+1;
        }
    }
    return i;
}

Search CFLib.org


Latest Additions

Raymond Camden added
QueryDeleteRows
November 04, 2017

Leigh added
nullPad
May 11, 2016

Raymond Camden added
stripHTML
May 10, 2016

Kevin Cotton added
date2ExcelDate
May 05, 2016

Raymond Camden added
CapFirst
April 25, 2016

Created by Raymond Camden / Design by Justin Johnson