darren
darren

Reputation: 1

Simple UDF to add space to a string

I am interested in creating a cold fusion UDF that will add a nonbreaking space to the beginning of a string if the the number of characters in the string is 1 or less. Any suggestions?

Upvotes: 0

Views: 1023

Answers (4)

Peter Boughton
Peter Boughton

Reputation: 112160

Here's a version that lets all parameters be passed in instead of being hardcoded.

Useful if your might at some point want more than just  , or could have different minimum lengths.

<cffunction name="prependIfShort" returntype="string" output="false">
    <cfargument name="String" type="string"  required />
    <cfargument name="Prefix" type="string"  required />
    <cfargument name="Limit"  type="numeric" required />

    <cfif len(Arguments.String) LTE Arguments.Limit >
        <cfreturn Arguments.Prefix & Arguments.String />
    <cfelse>
        <cfreturn Arguments.String />
    </cfif>
</cffunction>


Using it as asked in the question is like this:

prependIfShort( Input , '&nbsp;' , 1 )


Name could probably be improved, but it's the best I could think of at the moment.

Upvotes: 3

ale
ale

Reputation: 6430

function prependSpace(myString) {
  var returnString=myString;
  if (len(myString) LTE 1) {
    returnString="&nbsp;" & myString;
  }
  return returnString;
}

Upvotes: 2

Steve Withington
Steve Withington

Reputation: 480

// if using cf9+:
function padStr(str){
  return len(trim(str)) <= 1 ? 'nbsp;' & str : str
};

Upvotes: 1

mz_01
mz_01

Reputation: 495

To add some variety:

<cffunction name="padString" returnType="string" access="public" output="no">
    <cfargument name="input" type="string" required="yes">

    <CFRETURN ((len(ARGUMENTS.input) GT 1) ? ARGUMENTS.input : ("&nbsp;" & ARGUMENTS.input))>
</cffunction>

Upvotes: 2

Related Questions