Sunday, September 17, 2006

ASP Function to Capitalize the First Letter of All Words in a Sentence

Here's a function you can use that will capitalize the first letter of all words in a sentence. Simply pass in the text string containing the words you want capitalized.

You send in: "The quick brown fox"
You get out: "The Quick Brown Fox"

First call the function:
YourString="The quick brown fox"
strCaps = Capitalize(YourString)
The Function:
Function Capitalize(X)
'return a string with the first letter of the word capitalised
If IsNull(X) Then
Exit Function
lowercaseSTR = CStr(LCase(X))
OldC = " "
MyArray = Split(lowercaseSTR," ")
For IntI = LBound(MyArray) To UBound(MyArray)
For I = 1 To Len(MyArray(IntI))
If Len(MyArray(IntI)) = 1 Then
newString = newString & UCase(MyArray(IntI)) & " "
ElseIf I=1 Then
newString = newString & UCase(Mid(MyArray(IntI), I, 1))
ElseIf I = Len(MyArray(IntI)) Then
newString = newString & Mid(MyArray(IntI), I, 1) & " "
newString = newString & Mid(MyArray(IntI), I, 1)
End If
Next 'IntI
Capitalize = Trim(newString)
End If
End Function


Kyle said...

Great post, I need it for names stored in a database in all caps, so I expanded your function for my needs. Check it out.

Marcel B said...

I built this which works for me:-

function capit(thetext)
do while instr(intext," ")>0
chunk = left(intext, instr(intext," "))
outtext=outtext & " " & left(ucase(chunk),1) & right(chunk,len(chunk)-1)
intext= right(intext,len(intext)-instr(intext," "))
outtext=outtext & " " & left(ucase(intext),1) & right(intext,len(intext)-1)
end function

Anonymous said...

Awesome, this is exactly what I was looking for!