TypeScript String charAt()

🎓 Top 15 Udemy Courses (80-90% Discount): My Udemy Courses - Ramesh Fadatare — All my Udemy courses are real-time and project oriented courses.

▶️ Subscribe to My YouTube Channel (178K+ subscribers): Java Guides on YouTube

▶️ For AI, ChatGPT, Web, Tech, and Generative AI, subscribe to another channel: Ramesh Fadatare on YouTube

In this chapter, we will explore the charAt() method in TypeScript. This method is a built-in function that helps in retrieving a character at a specified index from a string. Understanding how to use charAt() is useful for manipulating and accessing characters within strings effectively.

Table of Contents

  1. Definition
  2. Syntax
  3. Examples
  4. Conclusion

1. Definition

The charAt() method returns the character at a specified index (position) in a string. If the index is out of range, it returns an empty string.

2. Syntax

string.charAt(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 string representing the character at the specified index. If the index is out of range, it returns an empty string.

3. Examples

Let's look at some examples to understand how charAt() works in TypeScript.

Example 1: Basic Usage

In this example, we retrieve characters from a string using valid indexes.

let str: string = "Hello, TypeScript!";
console.log(str.charAt(0)); // Output: H
console.log(str.charAt(7)); // Output: T
console.log(str.charAt(15)); // Output: t

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.charAt(20)); // Output: (empty string)

Example 3: Iterating Over String

In this example, we iterate over each character in the string using a loop.

let str: string = "TypeScript";
for (let i = 0; i < str.length; i++) {
  console.log(`Character at index ${i}: ${str.charAt(i)}`);
}
// Output:
// Character at index 0: T
// Character at index 1: y
// Character at index 2: p
// Character at index 3: e
// Character at index 4: S
// Character at index 5: c
// Character at index 6: r
// Character at index 7: i
// Character at index 8: p
// Character at index 9: t

4. Conclusion

In this chapter, we explored the charAt() method in TypeScript, which is used to retrieve a character at a specified index from a string. We covered its definition, syntax, parameters, return value, and provided several examples to demonstrate its usage.

My Top and Bestseller Udemy Courses. The sale is going on with a 70 - 80% discount. The discount coupon has been added to each course below:

Comments

Spring Boot 3 Paid Course Published for Free
on my Java Guides YouTube Channel

Subscribe to my YouTube Channel (165K+ subscribers):
Java Guides Channel

Top 10 My Udemy Courses with Huge Discount:
Udemy Courses - Ramesh Fadatare