JavaScript Objects: More on String Methods - The CharAt() Method
(Page 2 of 6 )
If you want to print a character in a specific location in a string, you can use the CharAt() method. No, not the carat you nut. We're not trying to improve your vision. That's what the gamma radiation from your monitor is for.
Here is program that uses the CharAt() method:
<html>
<body>
<script type="text/javascript">
var astring="Are you guys nerds?"
document.write(astring)
document.write("<br /><br />The fourth letter is: " + astring.charAt(4) + "<br />")
document.write("The third letter is: " + astring.charAt(2) + "<br />")
document.write("The twelfth letter is: " + astring.charAt(11))
</script>
</body>
</html>
The above code would display this:
Are you guys nerds?
The fourth letter is: y
The third letter is: e
The twelfth letter is: s
The CharCodeAt() Method
If you wanted to see the Unicode results of the preceding programming example (and let's face it you party animal, you know you want to), you could use the CharCodeAt() method. Wanna see this bad boy at work? Well here it is: BAM!
<html>
<body>
<script type="text/javascript">
var astring="Are you guys nerds?"
document.write(astring)
document.write("<br /><br />The Unicode for the fourth letter is: " + astring.charCodeAt(4) + "<br />")
document.write("The Unicode for the third letter is: " + astring.charCodeAt(2) + "<br />")
document.write("The Unicode for the twelfth letter is: " + astring.charCodeAt(11))
</script>
</body>
</html>
This program works like the previous program, except now it is returning the Unicode value of the characters instead. The result is this:
Are you guys nerds?
The Unicode for the fourth letter is: 121
The Unicode for the third letter is: 101
The Unicode for the twelfth letter is: 115
And that's my way of calling you guys nerds in Unicode. You got taken to the Pwn Shop.
Next: Working with the ConCat() Method >>
More JavaScript Articles
More By James Payne