Strings in TypeScript



In this tutorial, we will learn about strings in TypeScript. We will cover the basics of string manipulation, including creating, accessing, modifying, and performing operations on strings.


What is a String

A string in TypeScript is a sequence of characters. Strings in TypeScript are immutable, which means once created, they cannot be changed. Strings are used for storing and handling text data.


Creating Strings

Strings can be created in TypeScript using single quotes or double quotes:

let str: string = 'Hello, world!';
let str2: string = "Hello, world!";


Example 1: Initializing Strings

  1. Create a string variable and initialize it with a value.
  2. Print the string variable using console.log.

TypeScript Program

let str: string = 'Hello, world!';
console.log(str);

Output

Hello, world!


Example 2: Accessing Characters in a String

  1. Create a string variable and initialize it with a value.
  2. Access and print individual characters using array indexing.

TypeScript Program

let str: string = 'Hello';
console.log(str[0]); // Accessing using array indexing
console.log(str.charAt(1)); // using charAt method

Output

H
e


Example 3: Modifying Strings

  1. Create a string variable and initialize it with a value.
  2. Strings in TypeScript are immutable, so you cannot modify individual characters directly but can create new strings based on modifications.
  3. Print the modified string.

TypeScript Program

let str: string = 'Hello';
let modifiedStr: string = str.replace('H', 'J'); // Replacing a character
modifiedStr += ' World!'; // Appending new characters
console.log(modifiedStr);

Output

Jello World!


Example 4: String Concatenation

  1. Create two string variables and initialize them with values.
  2. Concatenate the strings using the + operator or the concat method.
  3. Print the concatenated string.

TypeScript Program

let str1: string = 'Hello';
let str2: string = ' World!';
let str3: string = str1 + str2; // Concatenating strings
console.log(str3);

Output

Hello World!


Example 5: Finding Substrings

  1. Create a string variable and initialize it with a value.
  2. Use the includes method to find a substring.
  3. Print the existence of the substring.

TypeScript Program

let str: string = 'Hello, world!';
if (str.includes('world')) {
  console.log('Substring found');
} else {
  console.log('Substring not found');
}

Output

Substring found


Example 6: String Length

  1. Create a string variable and initialize it with a value.
  2. Use the length property to get the length of the string.
  3. Print the length of the string.

TypeScript Program

let str: string = 'Hello, world!';
console.log('Length of the string:', str.length);

Output

Length of the string: 13