TypeScript String
In TypeScript, strings are used to represent textual data. They are primitive data types, meaning they are fundamental building blocks of the language and cannot be further broken down. Here's a comprehensive explanation of strings in TypeScript with examples:
String Definition and Syntax
Strings can be defined using single quotes ('), double quotes ("), or backticks (`).
- Single and double quotes are identical and can be used interchangeably.
- Backticks are used for template literals, which allow embedding expressions within the string.
Here are some examples:
Running the TypeScript compiler (tsc) will generate the following JavaScript code:
String Operations
TypeScript provides various string operations for manipulation and access:
Concatenation
Use the + operator to combine strings.
Access Characters
Use bracket notation to access individual characters by index (starting from 0).
String Concatenation and Template Literals
TypeScript supports string concatenation and template literals for dynamic string generation:
Both fullNameConcatenated and fullNameTemplate result in the same string: "Jack Sparrow". Template literals, denoted by backticks, allow embedding expressions within the string using ${}.
String Literal Types
TypeScript allows the definition of string literal types, which restrict a variable to a specific string value:
Here, status can only be assigned the values 'success' or 'error'. This helps catch potential errors at compile-time.
String Unions and Intersection
Typescript allows defining unions and intersections of string types.
Union
Represents a string that can be one of several values.
Intersection
Represents a string that must match all specified types.
String Utility Functions
Typescript provides additional utility functions for working with strings:
- String.fromCharCode(codePoint): string - Creates a string from a Unicode code point.
- String.fromCodePoint(...codePoints): string - Creates a string from an array of Unicode code points.
- String.prototype.codePointAt(index): number - Returns the Unicode code point at a given index.
These functions can be helpful for dealing with specific character encoding needs.
String Methods in TypeScript
TypeScript strings offer a plethora of built-in methods for manipulation and retrieval of information. These methods are essential for working with textual data effectively. Here's a detailed explanation of some key string methods in TypeScript with examples:
String Access and Modification
- charAt(index): string: Returns the character at the specified index (starting from 0).
- charCodeAt(index):number: Returns the Unicode code point of the character at the specified index.
- concat(...strings: string[]): string: Combines multiple strings into a single string.
- slice(start: number, end?: number): string: Extracts a substring from the string within the specified range.
- substring(start: number, end?: number): string: Similar to slice, but allows negative indexes for reverse selection.
- toUpperCase(): string: Converts the string to uppercase.
- toLowerCase(): string: Converts the string to lowercase.
- trim(): string: Removes leading and trailing whitespace from the string.
Search and Comparison
- indexOf(substr: string, start?: number): number: Returns the starting index of the first occurrence of substr in the string.
- lastIndexOf(substr: string, start?: number): number: Returns the starting index of the last occurrence of substr in the string.
- search(regexp: RegExp): number: Returns the index of the first match of the regular expression regexp in the string.
- includes(substr: string, start?: number): boolean: Checks if the string contains the substring substr.
- startsWith(substr: string): boolean: Checks if the string starts with the substring substr.
- endsWith(substr: string): boolean: Checks if the string ends with the substring substr.
String Replacement
- replace(regexp: RegExp, newSubstr: string): string: Replaces all occurrences of the regular expression regexp in the string with newSubstr.
- split(separator: string | RegExp): string[]: Splits the string into an array of substrings based on the specified separator.
Other Useful Methods
- match(regexp: RegExp): RegExpMatchArray | null: Returns an array containing information about the first match of the regular expression regexp in the string.
- localeCompare(str: string): number: Compares the string to another string based on the current locale.
- repeat(count: number): string: Creates a new string by repeating the original string count times.
Here are some additional points to note about strings in TypeScript:
- Strings are immutable in TypeScript. They cannot be modified after creation.
- To modify a string, you need to reassign a new string value.
- TypeScript provides type annotations for strings, which helps ensure type safety and avoid errors.
- You can use string literals and template literals as types for variables and function parameters.
Conclusion
TypeScript strings offer a powerful and flexible way to work with textual data. By understanding the various features and functionalities available, you can write clean, maintainable, and efficient code.