UDF simple para agregar espacio a una cadena

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?

preguntado el 28 de agosto de 11 a las 02:08

4 Respuestas

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 />
        <cfreturn Arguments.String />

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.

Respondido 28 ago 11, 17:08

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))>

Respondido 28 ago 11, 07:08

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

Respondido 28 ago 11, 17:08

He votado este one up because it'll work on all versions of CF from CF5 onwards, so strikes me as the solution with the most utility. It's good to see all the varying approaches people have though. - Adam Cameron

I almost voted it down because the code had a bug, but I decided to fix it instead. :) However, if I was doing this I'd do a parameterised version, and not waste time creating a temp variable. - Peter Boughton

@Peter: Thanks for the fix. Yes, not as elegant as it could be, but certainly good enough to give the OP a place to start. - de

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

Respondido 28 ago 11, 07:08

Why are you trimming the string? - Peter Boughton

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.