How can I pad a variable with spaces or other characters?

If you need to pad a ColdFusion variable with spaces then you can use the build in rjustify() and ljustify() functions. For example:

<cfset newText = rjustify("foo", 35)>
<cfoutput>#newText#</cfoutput>

If you ever find the need to pad a ColdFusion variable with non-space characters (i.e. Change 'name' to 'name-----'), then the repeatString() function is your friend. For example:

 

<cfset origText = "name">

<cfset paddingChar = "-">

<cfset paddingCount = 5>

<cfset newText = origText & repeatString(paddingChar, paddingCount)>

<cfoutput>#newText#</cfoutput>

Now lets get a little more advanced. Say you are trying to format an email and want to pad to a length minus the size of the string so that you can get rows of text to line up. All you need to do is use the len() function to account for the length of the text you are trying to pad.

 

<cfset origText = "name:">

<cfset paddingChar = "-">

<cfset paddingCount = 10>

<cfset newText = origText & repeatString(paddingChar, paddingCount - len(origText) ) >

<cfoutput>#newText#</cfoutput>Jeremy

You can easily put this into a custom function:

<cfscript>
function printWithPad(str,pad) {
	var padchar = '-';
	if(arrayLen(arguments) gte 3) padchar = arguments[3];
	if(len(str) gte pad) return str;
	return str & repeatString(padchar, pad - len(str));
}
</cfscript> 
<cfoutput>#printWithPad("name:",10)#</cfoutput>Jeremy<br />
<cfoutput>#printWithPad("country:",10)#</cfoutput>USA<br />

This question was written by Jeremy Petersen
It was last updated on September 5, 2006.

Categories

Display and Layout
Strings

Comments

comments powered by Disqus