String Manipulation in TypeScript

Introduction

Welcome to this lesson on TypeScript, where we will explore essential string manipulation features including string tokenization, string concatenation, trimming whitespace from strings, and type conversion operations. TypeScript builds upon JavaScript with added type safety and intelligence, providing a robust development environment.

Tokenizing a String in TypeScript

In TypeScript, we can utilize the split method from the String class to tokenize a string. With TypeScript's type system, we can explicitly specify types for more clarity and safety.

TypeScript
let sentence: string = "TypeScript is an amazing language!";
let tokens: string[] = sentence.split(" ");

tokens.forEach((token: string) => console.log(token));

// Output:
// TypeScript
// is
// an
// amazing
// language!

Here, we declare a string variable sentence and specify it should be treated as a string. The tokens variable is typed as a string array string[], providing clear expectations of the variable's contents. The forEach method iterates over each token, ensuring the type remains consistent throughout the operations.

Exploring String Concatenation

Trimming Whitespace from Strings

TypeScript supports the trim method to eliminate extra spaces, with the added benefit of type-checking:

let str: string = "    Hello, World!    "; // string with leading and trailing spaces
str = str.trim(); // remove leading and trailing spaces
console.log(str); // Output: "Hello, World!"
Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal