Jimmy Goodson
Jimmy Goodson

Reputation: 65

Add whitespace to string in Coldfusion

I need to add whitespace onto the end of a string.

ColdFusion seems to be automatically removing any whitespace I try to add, I'll sometimes get 1 empty space character but that's it.

I have an input field, a string, that can be up to 7 characters long. If the input is less than 7 characters, I'm to pad the end with spaces.

Does anyone know of a quick, easy, intuitive way to accomplish this using coldfusion. As little code as possible is preferred.

Some of the solutions I tried were:

 #LEFT(FORM.strInput & '       ', 7)#

 #LEFT(FORM.strInput & '        0', 7)#

 #REPLACE(LEFT(FORM.strInput & 0000000, 7), '0', ' ', 'all')#

<CFLOOP FROM="1" TO="7 - LEN(FORM.strInput)">
  <CFSET FORM.strInput = FORM.strInput & ' '>
</CFLOOP>

<CFLOOP FROM="1" TO="7 - LEN(FORM.strInput)">
  <CFSET FORM.strInput = FORM.strInput & '&nbsp;'>
</CFLOOP>

Upvotes: 1

Views: 1372

Answers (2)

James A Mohler
James A Mohler

Reputation: 11120

I like Scott's answer, but I would refine it a bit.

<script>
form.strInput &= repeatString(' ', max(7 - len(form.strInput), 0));
</script>

Upvotes: 2

Scott Stroz
Scott Stroz

Reputation: 7519

You can use repeatString()

<cfset form.strInput = form.strInput & repeatString( ' ', max( 7-len(form.strInput), 0 ) ) />

But, keep in mind, if you try to display multiple consecutive spaces on a web page, the browser will only 'display' the first one.

Upvotes: 5

Related Questions