In this chapter, we will explore the charCodeAt()
method in TypeScript. This method is a built-in function that helps in retrieving the Unicode value of the character at a specified index in a string. Understanding how to use charCodeAt()
is useful for manipulating and accessing the Unicode values of characters within strings.
Table of Contents
- Definition
- Syntax
- Examples
- Conclusion
1. Definition
The charCodeAt()
method returns the Unicode value of the character at a specified index (position) in a string. If the index is out of range, it returns NaN
.
2. Syntax
string.charCodeAt(index);
Parameters
index
: A number representing the position of the character you want to retrieve. The index starts from 0.
Return Value
The method returns a number representing the Unicode value of the character at the specified index. If the index is out of range, it returns NaN
.
3. Examples
Let's look at some examples to understand how charCodeAt()
works in TypeScript.
Example 1: Basic Usage
In this example, we retrieve the Unicode values of characters from a string using valid indexes.
let str: string = "Hello, TypeScript!";
console.log(str.charCodeAt(0)); // Output: 72 (Unicode value of 'H')
console.log(str.charCodeAt(7)); // Output: 84 (Unicode value of 'T')
console.log(str.charCodeAt(15)); // Output: 33 (Unicode value of '!')
Example 2: Index Out of Range
In this example, we use an index that is out of the range of the string length.
let str: string = "Hello, TypeScript!";
console.log(str.charCodeAt(20)); // Output: NaN
Example 3: Iterating Over String
In this example, we iterate over each character in the string and log its Unicode value.
let str: string = "TypeScript";
for (let i = 0; i < str.length; i++) {
console.log(`Unicode value of character at index ${i} (${str.charAt(i)}): ${str.charCodeAt(i)}`);
}
// Output:
// Unicode value of character at index 0 (T): 84
// Unicode value of character at index 1 (y): 121
// Unicode value of character at index 2 (p): 112
// Unicode value of character at index 3 (e): 101
// Unicode value of character at index 4 (S): 83
// Unicode value of character at index 5 (c): 99
// Unicode value of character at index 6 (r): 114
// Unicode value of character at index 7 (i): 105
// Unicode value of character at index 8 (p): 112
// Unicode value of character at index 9 (t): 116
4. Conclusion
In this chapter, we explored the charCodeAt()
method in TypeScript, which is used to retrieve the Unicode value of the character at a specified index in a string. We covered its definition, syntax, parameters, return value, and provided several examples to demonstrate its usage. Understanding how to use charCodeAt()
effectively can help in various string manipulation tasks in TypeScript, especially when dealing with Unicode values.
Comments
Post a Comment
Leave Comment