Learn TypeScript in Construct, part 11: Standard library

UpvoteUpvote 3 DownvoteDownvote

Index

Features on these Courses

Stats

160 visits, 176 views

Tools

Translations

This tutorial hasn't been translated.

License

This tutorial is licensed under CC BY-NC 4.0. Please refer to the license text if you wish to reuse, share or remix the content contained within this tutorial.

Published on 30 Jul, 2025. Last updated 31 Jul, 2025

String methods

Previously we covered strings like "Hello world". In TypeScript, strings are also a special kind of object, and so have properties and methods you can call on them. For example "Hello".length is 5, as the string has 5 characters.

You may have noticed that arrays are also a special kind of object in TypeScript. In fact in TypeScript pretty much everything is an object! Here are some useful string methods that you can try out in the console.

// Try entering in to the browser console:

// toLowerCase() returns a new string with lower case
"Hello World".toLowerCase()	// "hello world"

// toUpperCase() returns a new string with upper case
"Hello World".toUpperCase();	// "HELLO WORLD"

// includes() returns a boolean indicating if a given
// string appears in the string it is called on
"Hello world".includes("world")	// true
"Hello world".includes("pizza")	// false

// startsWith() returns a boolean indicating if the
// string it is called on starts with a given string
"Hello world".startsWith("Hello")	// true
"Hello world".startsWith("Pizza")	// false

// endsWith() does the same but for the end of the string
"Hello world".endsWith("world")		// true
"Hello world".endsWith("pizza")		// false

// repeat() returns a new string which repeats the
// string it is called on a number of times
"😀".repeat(5)		// 😀😀😀😀😀

// split() returns an array of strings separated
// by a given character
"pizza,chocolate,burrito".split(",")
// returns an array of strings:
// ["pizza", "chocolate", "burrito"]

Strings can also be converted to an array of strings, with one character per element, using the spread operator .... The below example shows how the array can then be used to access the number of characters and a character at a specific index.

// A string with an emoji
let str = "Hi😀";

// Convert the string to an array.
// TypeScript infers this is an array of strings.
let arr = [...str];

// The array now has:
// [ "H", "i", "😀" ]

// Log details about the string from the array
console.log(`The array length is ${arr.length}`);
console.log(`The 3rd character is ${arr[2]}`);

You can also use a for-of loop to iterate the characters of the string directly.

// A string with an emoji
let str = "Hi😀";

// Use a for-of loop to repeat for each character
for (let ch of str)
{
	console.log(`String character: ${ch}`);
}

There's lots more you can do with strings in TypeScript. See the String MDN documentation for more.

  • 0 Comments

Want to leave a comment? Login or Register an account!