• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 286
  • Last Modified:

letter convertion

hi

1] how can i convert the first and last letter of a word to uppercase with javascript.

sample:

SmarT

2] how to convert the first letter to uppercase with javascript.

sample

Smart

3] and how convert the last letter to uppercase with javascript.

sample:

smarT

please advice with code for all three samples apart
0
eaweb
Asked:
eaweb
  • 2
1 Solution
 
BogoJokerCommented:
I don't know exactly how to convert a character to uppercase using character codes, but I do know how to convert a string to uppercase!

<html>
<head>
<script type="text/javascript">
var str = "smart";
document.write("Original: " + str);
document.write("<br>");
var str1 = str.substr(0,1);
var str2 = str.substr(1,str.length-2);
var str3 = str.substr(str.length-1, 1);
var result1 = str1.toUpperCase() + str2 + str3.toUpperCase();
var result2 = str1.toUpperCase() + str2 + str3;
var result3 = str1 + str2 + str3.toUpperCase();
document.write("1: " + result1);
document.write("<br>");
document.write("2: " + result2);
document.write("<br>");
document.write("3: " + result3);
</script>
</head>
</html>


Notice:
str1 holds the first letter
str2 holds the middle
str3 holds the last letter

I started with the all lowercase string "smart".  The middle and ends remain UNCHANGED but for the toUpperCase() requirements.
You could actually specify toLowerCase() if that be the case for parts you do no want capitalized.

Joe P
0
 
WilliamFrantzCommented:
BogoJoker has a good approach, but watch out for short strings.  For example, you probably want "i" to become "I" but the routine above might crash at str.substr(1, str.length-2) since str.length-2 will be negative.
0
 
BogoJokerCommented:
Good Point William Frantz!
You can add an extra check at the top:

if (str.length == 1)
  // Capitalize this single character
if (str.length == 2)
 // Do as you wish with this

Then the rest is normal.
0

Featured Post

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now