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;
}
blog comments powered by Disqus

Search CFLib.org


Latest Additions

Kevin Cotton added
date2ExcelDate
May 5, 2016

Raymond Camden added
CapFirst
April 25, 2016

Chris Wigginton added
loremIpsum
January 18, 2016

Gary Stanton added
calculateArrival...
November 19, 2015

Sebastiaan Naafs - van Dijk added
getDaysInQuarter
November 13, 2015

Created by Raymond Camden / Design by Justin Johnson