• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 289
  • 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
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

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