Welcome to an engaging TypeScript session! In this unit, we will delve deeper into handling string data. Consider situations in which you have to analyze text data, like constructing a web scraper or developing a text-based algorithm to interpret user reviews of a website. All these cases require efficient handling of strings, which involves analyzing and manipulating them. In this lesson, we will focus on how to traverse strings and perform operations on each character using TypeScript
. An advantage of TypeScript
is its powerful type system, which allows us to specify and enforce string types in our code.
The objective of this lesson is to become proficient in using TypeScript
loops with a specific emphasis on strings. We will explore the techniques of string indexing and practice character operations using TypeScript
's type annotations and functions.
Characters can be manipulated using their ASCII values. ASCII (American Standard Code for Information Interchange) is a character encoding standard used to represent text in computers and other devices that use text. Every character has a unique ASCII value.
You can convert a character into its ASCII value using the charCodeAt()
method with type annotations:
TypeScript1let c: string = 'A'; 2let asciiVal: number = c.charCodeAt(0); 3console.log(`The ASCII value of ${c} is: ${asciiVal}`); 4// Prints: The ASCII value of A is: 65
Similarly, you can convert an ASCII value back to its corresponding character using String.fromCharCode()
:
TypeScript1let asciiVal: number = 65; 2let c: string = String.fromCharCode(asciiVal); 3console.log(`The character of ASCII value ${asciiVal} is: ${c}`); 4// Prints: The character of ASCII value 65 is: A
Manipulating the ASCII value of characters can be quite useful in certain situations. For example, to convert a lowercase letter to uppercase (or vice versa), you could subtract (or add) 32 to the character's ASCII value.
Strings in TypeScript
, just like in other languages, work with a zero-based indexing system. This means that you can access specific characters in a string by using their position.
In TypeScript
, accessing an index that does not exist will not immediately cause a runtime error, but checking is mandatory to ensure the index is within bounds:
TypeScript1let text: string = "Hello, TypeScript!"; 2let index: number = 9; 3 4if (index < text.length) { 5 let charAtIndex: string = text.charAt(index); 6 console.log(`The character at index ${index} is: ${charAtIndex}`); 7} else { 8 console.log(`The index ${index} is out of bounds for the string!`); 9} 10 11// Prints: The character at index 9 is: p
Let's now explore character operations in TypeScript
. String methods such as toUpperCase()
and toLowerCase()
are used to change the case of a character, with added type annotations for clarity.
- Using
toUpperCase()
andtoLowerCase()
to change the case of characters:
TypeScript1let s: string = "mark"; 2let result: string = ''; 3for (let i = 0; i < s.length; i++) { 4 result += s.charAt(i).toUpperCase(); 5} 6console.log(result); // Prints: 'MARK' 7 8s = "Mark"; 9result = ''; 10for (let i = 0; i < s.length; i++) { 11 result += s.charAt(i).toLowerCase(); 12} 13console.log(result); // Prints: 'mark'
- Implementing custom functions to check the case of characters with
TypeScript
typings:
TypeScript1function isLowerCase(char: string): boolean { 2 return char === char.toLowerCase() && char !== char.toUpperCase(); 3} 4 5function isUpperCase(char: string): boolean { 6 return char === char.toUpperCase() && char !== char.toLowerCase(); 7} 8 9console.log("Is 'a' lowercase? " + isLowerCase('a')); // Prints: true 10console.log("Is 'B' lowercase? " + isLowerCase('B')); // Prints: false 11 12console.log("Is 'a' uppercase? " + isUpperCase('a')); // Prints: false 13console.log("Is 'B' uppercase? " + isUpperCase('B')); // Prints: true
- Checking whether a character is a letter, digit, or alphanumeric using regular expressions:
TypeScript1function isLetter(char: string): boolean { 2 // Checks if the character is a single English letter (either lowercase or uppercase) 3 return /^[a-zA-Z]$/.test(char); 4} 5 6function isDigit(char: string): boolean { 7 // Checks if the character is a single digit (0-9) 8 return /^[0-9]$/.test(char); 9} 10 11function isLetterOrDigit(char: string): boolean { 12 // Checks if the character is a single English letter or a digit 13 return /^[a-zA-Z0-9]$/.test(char); 14} 15 16console.log(isLetter('C')); // Prints: true 17console.log(isLetter('+')); // Prints: false 18 19console.log(isDigit('9')); // Prints: true 20console.log(isDigit('D')); // Prints: false 21 22console.log(isLetterOrDigit('6')); // Prints: true 23console.log(isLetterOrDigit('k')); // Prints: true 24console.log(isLetterOrDigit('?')); // Prints: false
Regular Expressions:
- Regular expressions, often abbreviated as regex, are sequences of characters that form a search pattern. They are mainly used for pattern matching with strings.
- In this context, the regex
/^[a-zA-Z]$/
checks if a single character string is either a lowercase (a-z
) or uppercase (A-Z
) English letter. The^
and$
symbols ensure the match is done on the entire string, meaning it should be exactly one letter.
Excellent work! We have learned how to work with strings in TypeScript
by looping over them, managing string indices, and manipulating characters using TypeScript
methods. Moreover, we have explored strategies to manage out-of-bounds indices while dealing with strings in our programs.
Real-world problems abound where string operations can be handy. From designing smart typewriters and web scrapers to crafting AI bots, mastering string operations is a valuable skill in the world of programming. Therefore, don't waste any time! Jump into the practice problems to reinforce your learning. Your journey is just beginning — see you in the upcoming sessions!