What is string.charAt() in TypeScript?
Overview
TypeScript is a superset of JavaScript. This means that it is the parent of JavaScript. The cool thing about it is that it gives us the ability to do more compared to JavaScript. Moreover, wherever JavaScript runs, TypeScript runs as well.
The charAt() method in TypeScript is used to return the character of a string at a specified index.
Syntax
string.charAt(index)
Syntax for charAt() in TypeScript
Parameters
index: This is the index of the character we want to get. This is an integer value.
Return value
The value returned is a single character. If the character is not found, then nothing is returned.
Code example
export {}// create some strings.let name:string = "Theodore"let role:string = "Software Developer"let nickName:string = "Kcee"let hubby:string = "Coding"// get some characterslet char1 = name.charAt(2)let char2 = role.charAt(0)let char3 = nickName.charAt(5)let char4 = hubby.charAt(1)// print the charactersconsole.log(char1) // "e"console.log(char2) // "S"console.log(char3) // nothingconsole.log(char4) // "o"
Explanation
- Line 1: We tell TypeScript that our file is a module of its own scope so as to avoid any error related to variable naming and the
letkeyword. - Lines 4-7: We create some strings.
- Lines 10-13: Using the
charAt()method, we get some characters from the strings we created. - Lines 16-19: We print the characters to the console.