Language: EN

typescript-tipo-string

The String Type in TypeScript

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 by 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 or the concat method and 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

Methods and properties of string

TypeScript provides a variety of methods and properties for manipulating strings. Let’s take a look at some of the most commonly used.