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 numb开发者_高级运维er of characters in the string is 1 or less. Any suggestions?
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 , ' ' , 1 )
Name could probably be improved, but it's the best I could think of at the moment.
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 : (" " & ARGUMENTS.input))>
</cffunction>
function prependSpace(myString) {
var returnString=myString;
if (len(myString) LTE 1) {
returnString=" " & myString;
}
return returnString;
}
// if using cf9+:
function padStr(str){
return len(trim(str)) <= 1 ? 'nbsp;' & str : str
};
精彩评论