CFLib.org – Common Function Library Project

sluggify(str[, spacer])

Last updated June 11, 2009

author

Michael Haggerty

Version: 1 | Requires: CF6 | Library: StrLib

Description:
This function will take any string and replace all of the non-alphanumeric characters with the spacer of your choice (default is '-').

Return Values:
Returns a string.

Example:

<cfset toBeSlugged = "This is a (very) nonalphanumeric, string" />
<cfset slug = sluggify(toBeSlugged) />
<cfoutput>#slug#</cfoutput>

Parameters:

Name Description Required
str String to modify. Yes
spacer Character used for spaces. Defaults to -. No

Full UDF Source:

<!---
 Converts a string into a pretty URL safe slug
 
 @param str 	 String to modify. (Required)
 @param spacer 	 Character used for spaces. Defaults to -. (Optional)
 @return Returns a string. 
 @author Michael Haggerty (mike@mikehaggerty.net) 
 @version 1, June 11, 2009 
--->
<cffunction name="sluggify" output="false" returnType="string">
	<cfargument name="str">
	<cfargument name="spacer" default="-">
	
	<cfset var ret = "" />
	
	<cfset str = lCase(trim(str)) />
	<cfset str = reReplace(str, "[^a-z0-9-]", "#spacer#", "all") />
	<cfset ret = reReplace(str, "#spacer#+", "#spacer#", "all") />
	
	<cfif left(ret, 1) eq "#spacer#">
		<cfset ret = right(ret, len(ret)-1) />
	</cfif>
	<cfif right(ret, 1) eq "#spacer#">
		<cfset ret = left(ret, len(ret)-1) />
	</cfif>
	
	<cfreturn ret />
</cffunction>
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