Skip to content

TypeScript - Strings

Strings represent sequences of characters and are one of the most fundamental data types in TypeScript and JavaScript. They are used to store text data.

TypeScript uses the string type annotation for variables that hold string values.

Strings can be created using single quotes ('), double quotes ("), or backticks (`).

let singleQuote: string = 'Hello';
let doubleQuote: string = "World";
let greeting: string = singleQuote + ' ' + doubleQuote; // Concatenation
console.log(greeting); // Output: Hello World

Template literals, enclosed in backticks (`), are the modern and preferred way to work with strings, especially when embedding expressions or creating multi-line strings.

  • Embedded Expressions: Use ${expression} syntax to embed variables or any valid JavaScript expression directly within the string.
  • Multi-line Strings: Template literals respect newlines within the backticks.
let userName: string = "Alice";
let userAge: number = 30;
// Using embedded expressions
let message: string = `Welcome, ${userName}! You are ${userAge} years old.`;
console.log(message);
// Output: Welcome, Alice! You are 30 years old.
// Multi-line string
let poem: string = `Roses are red,
Violets are blue,
TypeScript is fun,
And so are you!`;
console.log("\nPoem:\n" + poem);

Strings in TypeScript (inheriting from JavaScript) have built-in properties and methods for manipulation:

Property/MethodDescriptionExample
lengthReturns the number of characters in the string.'hello'.length is 5
charAt(index)Returns the character at the specified zero-based index.'abc'.charAt(1) is 'b'
charCodeAt(index)Returns the Unicode value (number) of the character at the specified index.'abc'.charCodeAt(1) is 98 (Unicode for ‘b’)
concat(str1, str2, ...)Joins two or more strings.'Hello'.concat(' ', 'World') is 'Hello World' (Same as + operator)
indexOf(searchValue, fromIndex?)Returns the index of the first occurrence of searchValue, or -1 if not found. Optional fromIndex starts search.'hello world'.indexOf('o') is 4
lastIndexOf(searchValue, fromIndex?)Returns the index of the last occurrence of searchValue, or -1 if not found.'hello world'.lastIndexOf('o') is 7
slice(startIndex, endIndex?)Extracts a section of the string and returns it as a new string. endIndex is optional and exclusive.'abcdef'.slice(1, 4) is 'bcd'
substring(startIndex, endIndex?)Similar to slice, but handles arguments differently if startIndex > endIndex.'abcdef'.substring(1, 4) is 'bcd'
substr(startIndex, length?)(Legacy) Extracts a substring starting at startIndex with a specified length.'abcdef'.substr(1, 3) is 'bcd'
split(separator?, limit?)Splits the string into an array of substrings based on the separator.'a,b,c'.split(',') is ['a', 'b', 'c']
replace(searchValue, newValue)Returns a new string with the first occurrence (or all if searchValue is a global regex) replaced.'hello'.replace('l', 'X') is 'heXlo'
replaceAll(searchValue, newValue)(ES2021) Returns a new string with all occurrences replaced.'hello'.replaceAll('l', 'X') is 'heXXo'
toLowerCase()Returns the string converted to lowercase.'HeLLo'.toLowerCase() is 'hello'
toUpperCase()Returns the string converted to uppercase.'HeLLo'.toUpperCase() is 'HELLO'
trim()Removes whitespace from both ends of the string.' hello '.trim() is 'hello'
trimStart() / trimLeft()Removes whitespace from the beginning of the string.' hello '.trimStart() is 'hello '
trimEnd() / trimRight()Removes whitespace from the end of the string.' hello '.trimEnd() is ' hello'
startsWith(searchString, position?)Checks if the string begins with searchString.'hello'.startsWith('he') is true
endsWith(searchString, length?)Checks if the string ends with searchString.'hello'.endsWith('lo') is true
includes(searchString, position?)Checks if the string contains searchString.'hello'.includes('ell') is true
padStart(targetLength, padString?)Pads the start of the string with padString until it reaches targetLength.'5'.padStart(3, '0') is '005'
padEnd(targetLength, padString?)Pads the end of the string with padString until it reaches targetLength.'5'.padEnd(3, '0') is '500'

Strings in JavaScript and TypeScript are immutable. This means that string methods do not modify the original string; they always return a new string with the changes.

let originalString: string = "TypeScript";
let upperString = originalString.toUpperCase();
console.log(originalString); // Output: TypeScript (original is unchanged)
console.log(upperString); // Output: TYPESCRIPT (new string is returned)

While you can technically create strings using the String constructor (new String('hello')), this creates an object wrapper around the primitive string. It’s generally recommended to use string literals ('hello', "hello", `hello`) which create primitive string values, as they are more performant and behave more predictably with operators like typeof and ===.

let primitiveStr: string = "test";
let objectStr: String = new String("test");
console.log(typeof primitiveStr); // Output: string
console.log(typeof objectStr); // Output: object
console.log(primitiveStr === "test"); // Output: true
console.log(objectStr === "test"); // Output: false (object vs primitive)
console.log(objectStr.valueOf() === "test"); // Output: true (use valueOf() to get primitive)