TypeScript character at specific index and index of character in string

Introduction :

In this tutorial, we will learn how to find the character of a string at a specific index in typescript i.e. we will read the character using its index. We will also learn how to find the index of a character in a string with examples.

Find the character using an index in typescript :

Typescript provides one method called charAt that returns the character of a string based on its index. This method is defined as below :

str.charAt(index)

Arguments and return value :

The only argument is the index of the character that we want. The index lies between 0 to length-1. All characters in a string indexed from left to right and it starts at 0. The first character has index 0, the second has 1 etc. It returns the character for that index.

Example of charAt() :

let str : string = "Hello";

console.log(str.charAt(0));
console.log(str.charAt(1));
console.log(str.charAt(2));
console.log(str.charAt(3));
console.log(str.charAt(4));

Output :

H
e
l
l
o

Find the index of a character in a string :

Typescript provides one method called indexOf to find out the index of a specific character in a string. It checks for the first occurrence of the character and returns its index if found. If the index is not found, it returns -1. This method is defined as below :

str.indexOf(char[,from])

Arguments and return value :

It takes two arguments: char and from(optional).

  1. char is the character or a substring that we are searching for.
  2. from is the index to start the search from.

It returns the index of the first occurrence of the substring or character. It returns -1 if not found.

Example of indexOf :

let str : string = "Hello";

console.log(`H => ${str.indexOf('H')}`);
console.log(`e => ${str.indexOf('e')}`);
console.log(`l => ${str.indexOf('l')}`);
console.log(`l from index 3 => ${str.indexOf('l',3)}`);
console.log(`lo => ${str.indexOf('lo')}`);
console.log(`oh => ${str.indexOf('oh')}`);

It will print the below output :

H => 0
e => 1
l => 2
l from index 3 => 3
lo => 3
oh => -1

In this example, we have explained all different types of examples. We can easily check the return value of indexOf to determine if a character or substring exists in a string or not.

Typescript indexof character string

Conclusion :

In this example, we have learned how to use charAt and indexOf methods with different examples. Try to go through the examples and drop one comment below if you have any queries.