In TypeScript, the string type is used to represent sequences of characters. Strings can be defined using single quotes ('), double quotes ("), or backticks (`) for template strings.
let message: string = "Hello, TypeScript!";
let greeting: string = 'Welcome!';
let template: string = `This is a TypeScript message`;
Template Strings
Template strings allow embedding expressions, making it easier to construct complex strings. They are delimited with backticks (`) and can contain interpolated expressions using ${}.
let name: string = "Luis";
let age: number = 30;
let message: string = `Hello, my name is ${name} and I am ${age} years old.`;
console.log(message); // "Hello, my name is Luis and I am 30 years old."
Escaping Characters
To include special characters in a string, escape sequences are used.
\n: New line\t: Tab\\: Backslash\': Single quote\": Double quote
let multiline: string = "Line 1\nLine 2";
console.log(multiline);
// Line 1
// Line 2
String Concatenation
String concatenation can be performed using the + operator, the concat method, or template strings.
Using the + operator
let greeting: string = "Hello, " + name + ". Welcome to " + text + "!";
console.log(greeting); // "Hello, Luis. Welcome to TypeScript!"
Using concat
let concatenatedGreeting: string = greeting.concat(" Enjoy your learning!");
console.log(concatenatedGreeting); // "Hello, Luis. Welcome to TypeScript! Enjoy your learning!"
Using template strings
let templateGreeting: string = `Hello, ${name}. Welcome to ${text}!`;
console.log(templateGreeting); // "Hello, Luis. Welcome to TypeScript!"
String Comparison
Strings can be compared using comparison operators (<, >, <=, >=, ==, !=, ===, !==). Comparisons are case-sensitive.
let string1: string = "abc";
let string2: string = "Abc";
console.log(string1 === string2); // false
console.log(string1.toLowerCase() === string2.toLowerCase()); // true
String Methods and Properties
TypeScript provides a variety of methods and properties for manipulating strings. Let’s look at some of the most commonly used ones.
