Java Reference
In-Depth Information
That completes the example, but before moving on, it's worth noting that this example is just that—an
example of using
charCodeAt()
. In practice, it would be much easier to just write
if (char >= "A" && char <= "Z")
rather than
if (charCode >= "A".charCodeAt(0) && charCode <= "Z".charCodeAt(0))
which you have used here.
Converting Character Codes to a String—the fromCharCode() Method
You can think of the method
fromCharCode()
as the opposite of
charCodeAt()
, in that you pass it a
series of comma‐separated numbers representing character codes, and it converts them to a single string.
However, the
fromCharCode()
method is unusual in that it's a
static
method—you don't need to
have created a
String
object to use it with; it's always available to you.
For example, the following lines put the string
"ABC"
into the variable
myString
:
var myString = String.fromCharCode(65,66,67);
The
fromCharCode()
method can be very useful when used with variables. For example, to build up
a string consisting of all the uppercase letters of the alphabet, you could use the following code:
var myString = "";
var charCode;
for (charCode = 65; charCode <= 90; charCode++) {
myString = myString + String.fromCharCode(charCode);
}
document.write(myString);
You use the
for
loop to select each character from A to Z in turn and concatenate this to
myString
.
Note that although this is fine as an example, it is more efficient and less memory‐hungry to simply
write this instead:
var myString = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
removing Leading and trailing Whitespace—the trim() Method
When working with user‐provided data, you're never guaranteed that the users input their data
exactly how you want them to. Therefore, it's always best to assume user input is incorrect, and it's
your job to make it correct.
The process of scrubbing data is dependent on the specific needs of your application, but you'll
commonly want to trim the whitespace from the start and end of the string. For this,
String
objects