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 (`).

  1. Single and double quotes are identical and can be used interchangeably.
  2. Backticks are used for template literals, which allow embedding expressions within the string.

Here are some examples:

// Single quote const name: string = 'John Doe';
// Double quote const message: string = "Hello, world!";
// Backtick (template literal) const greeting: string = `My name is ${name}`;

Running the TypeScript compiler (tsc) will generate the following JavaScript code:

// Single quote const name = 'Jack Sparrow';
// Double quote const message = "Hello, world!";
// Backtick (template literal) const greeting = `My name is ${name}`;

String Operations

TypeScript provides various string operations for manipulation and access:

Concatenation

Use the + operator to combine strings.

const fullName: string = name + " " + "Sparrow"; // Jack Sparrow

Access Characters

Use bracket notation to access individual characters by index (starting from 0).

const firstCharacter: string = name[0]; // J

String Concatenation and Template Literals

TypeScript supports string concatenation and template literals for dynamic string generation:

let firstName: string = 'Jack'; let lastName: string = 'Sparrow'; // String concatenation let fullNameConcatenated: string = firstName + ' ' + lastName; // Template literal let fullNameTemplate: string = `${firstName} ${lastName}`;

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:

let status: 'success' 'error'; status = 'success'; // valid // status = 'warning'; // Error: Type '"warning"' is not assignable to type '"success" "error"'

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.

type Greeting = "Hello" "Hi" "Good morning"; let greeting: Greeting = "Hi";

Intersection

Represents a string that must match all specified types.

type LongName = string & { length: >= 5 }; let longName: LongName = "Jack Sparrow";

String Utility Functions

Typescript provides additional utility functions for working with strings:

  1. String.fromCharCode(codePoint): string - Creates a string from a Unicode code point.
  2. String.fromCodePoint(...codePoints): string - Creates a string from an array of Unicode code points.
  3. 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

  1. charAt(index): string: Returns the character at the specified index (starting from 0).
  2. charCodeAt(index):number: Returns the Unicode code point of the character at the specified index.
  3. concat(...strings: string[]): string: Combines multiple strings into a single string.
  4. slice(start: number, end?: number): string: Extracts a substring from the string within the specified range.
  5. substring(start: number, end?: number): string: Similar to slice, but allows negative indexes for reverse selection.
  6. toUpperCase(): string: Converts the string to uppercase.
  7. toLowerCase(): string: Converts the string to lowercase.
  8. trim(): string: Removes leading and trailing whitespace from the string.
Examples:
const str = "Hello World!"; console.log(str.charAt(0)); // Output: H console.log(str.charCodeAt(4)); // Output: 108 (unicode code point for "l") console.log(str.concat(" How are you?")); // Output: Hello World! How are you? console.log(str.slice(6, 11)); // Output: World console.log(str.substring(0, 5)); // Output: Hello console.log(str.toUpperCase()); // Output: HELLO WORLD! console.log(str.trim()); // Output: Hello World!

Search and Comparison

  1. indexOf(substr: string, start?: number): number: Returns the starting index of the first occurrence of substr in the string.
  2. lastIndexOf(substr: string, start?: number): number: Returns the starting index of the last occurrence of substr in the string.
  3. search(regexp: RegExp): number: Returns the index of the first match of the regular expression regexp in the string.
  4. includes(substr: string, start?: number): boolean: Checks if the string contains the substring substr.
  5. startsWith(substr: string): boolean: Checks if the string starts with the substring substr.
  6. endsWith(substr: string): boolean: Checks if the string ends with the substring substr.
Examples:
const str = "This is a sentence."; console.log(str.indexOf("is")); // Output: 2 console.log(str.lastIndexOf("is")); // Output: 11 console.log(str.search(/\s/)); // Output: 3 (index of first whitespace) console.log(str.includes("sentence")); // Output: true console.log(str.startsWith("This")); // Output: true console.log(str.endsWith(".")); // Output: true

String Replacement

  1. replace(regexp: RegExp, newSubstr: string): string: Replaces all occurrences of the regular expression regexp in the string with newSubstr.
  2. split(separator: string | RegExp): string[]: Splits the string into an array of substrings based on the specified separator.
Examples:
const str = "This is a string with some numbers: 12345."; console.log(str.replace(/\d/g, "*")); // Output: This is a string with some numbers: *****. console.log(str.split(" ")); // Output: ["This", "is", "a", "string", "with", "some", "numbers:", "12345."]

Other Useful Methods

  1. match(regexp: RegExp): RegExpMatchArray | null: Returns an array containing information about the first match of the regular expression regexp in the string.
  2. localeCompare(str: string): number: Compares the string to another string based on the current locale.
  3. repeat(count: number): string: Creates a new string by repeating the original string count times.
Examples:
const str = "Hello World!"; console.log(str.match(/\w+/g)); // Output: ["Hello", "World"] console.log(str.localeCompare("World")); // Output: 1 (positive value indicates str is greater than "World") console.log(str.repeat(3)); // Output: Hello World!Hello World!Hello World!

Here are some additional points to note about strings in TypeScript:

  1. Strings are immutable in TypeScript. They cannot be modified after creation.
  2. To modify a string, you need to reassign a new string value.
  3. TypeScript provides type annotations for strings, which helps ensure type safety and avoid errors.
  4. 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.