How To Create And Work With TypeScript Strings

How To Create And Work With TypeScript Strings

TypeScript strings provide essential manipulation techniques you will need when manipulating textual data. This guide will show you in detail how to use them in your applications.

Create TypeScript Strings

TypeScript uses the string type to hold sequences of characters. It uses UTF-16 under the hood as the format for these strings. There are also String objects, which are instances of a class and not a data type.

String Literals

To declare a value of the string type, you can use string literals. They are sequences of characters enclosed by single or double quotes.

These are valid string literals in TypeScript:

'LearnShareIT'
"TypeScript"
''

Use the assignment operator when you want to assign these values to variables:

let a = 'LearnShareIT';
console.log(a);

Output

LearnShareIT

In this example, the compiler will automatically infer the type of variable using the value you have given it. You can also explicitly specify this type with the type annotation feature of TypeScript:

let a: string = 'LearnShareIT';

The use of type annotation isn’t necessary in this case because the string type will be correctly inferred by TypeScript anyway. But it will be helpful when you need to lock in the type of a string variable in advance. The type-checking system will make sure this type annotation is respected throughout the whole program.

String()

You can also use String() as a function to create a string from a value of another data type or simply from a string literal.

Example

let year: number = 2022;
let yearStr = String(year);
console.log(year);
console.log(typeof year);
console.log(yearStr);
console.log(typeof yearStr);

Output

2022
number
2022
string

As you can see, the variables year and yearStr produce similar output with the console.log() function. But they are actually of two different types.

When used in conjunction with the new keyword, String() becomes a constructor. In this case, it returns a String object, not a string value.

Example

let a = String('LearnShareIT');
let b = new String('LearnShareIT');
console.log(typeof a);
console.log(typeof b);

Output

string
object

You will barely need this use of String(). All methods of the String class work with string values as well.

Special Characters

You can use the backslash (\) as an escape character for special characters such as newline (\n). Notice how the string has been broken up into two lines when you insert \n in the middle of the string literal:

let a = 'LearnShareIT\nWelcome to our site!'
console.log(a);

Output

LearnShareIT
Welcome to our site!

You can use the backslash to insert other special characters like tab (\t), carriage return (\r), or backspace (\b). It also comes in handy when you need to put single quotes inside a string denoted by single quotes or double quotes inside a string denoted by double quotes.

Example

let a = 'He said, \'Let\'s get out!\''
console.log(a);

Output

He said, 'Let's get out!'

If you don’t use these backslashes, TypeScript will interpret them as the single quote before Let as the character for ending the whole string. The rest of the literal will make no sense and result in syntax errors like this:

let a = 'He said, 'Let's get out!''
console.log(a);

Output

typescript.ts:1:20 - error TS1005: ',' expected
typescript.ts:1:36 - error TS1002: Unterminated string literal.

Template Strings

There is actually another way to denote string literals in TypeScript: with the backtick (`):

let a = `John`;

But the main use of this character is in template strings (also known as template literals). They allow you to easily create multi-line strings, use embedded expressions to interpolate strings, and create tagged templates.

Note: this feature is only available in ECMAScript 2015 (ES6) or newer.

With a template literal, you don’t need escape characters to write your string in multiple lines:

let message = `This is LearnShareIT
Welcome to our site!`;
console.log(message);

Output

This is LearnShareIT
Welcome to our site!

You can also combine the result of other expressions into your string with ease. This is how you can use template literals with the ${expression} form:

let a = 3;
let b = 4;
let output = `The result of a + b is ${a + b}`;
console.log(output);

Output

The result of a + b is 7

Common String Operations

You can use the length property to get the number of characters in a string:

let str = 'learnshareit';
console.log(str.length);

Output

12

The plus operator is one of the most common ways to concatenate two or more strings in TypeScript.

Example

let site = 'learnshare';
let tld = 'com';
let domain = site + '.' + tld;
console.log(domain);

Output

learnshareit.com

It is important to note that not all operands have to be string values. The runtime environment will try to convert non-string values to strings before carrying out the concatenation.

In the following example, the number value 4 will be converted to a string with the function toString() before being appended to the prefix S:

let prefix = 'S';
let gen = 4
let output = prefix + gen;
console.log(output);

Output

S4

The shorthand assignment operator (+=) is useful when you want to append a string to an existing string and assign the result to the original string:

let output = 'S';
let gen = 4
output += gen;
console.log(output);

Output

S4

The subscript operator allows you to access characters in a string using their indexes. Since TypeScript uses zero-based indexing, this example prints the fourth character in the string ‘orange’:

let str = 'orange';
console.log(str[3]);

Output

n

Common String Methods

charAt()

In addition to the subscript operator, you can also use this method to return the character at a specified position in the string:

let str = 'orange';
console.log(str.charAt(3));

Output

n

indexOf()

This method returns the index of a substring you want to look for in a string. If the substring appears multiple times, only the index of the first occurrence is returned:

let str = 'learnshareit';
console.log(str.indexOf('a'));

Output

2

includes()

This method checks if a substring exists within a string and returns a boolean output:

let str = 'learnshareit';
console.log(str.includes('share'));

Output

true

toLowerCase(), toUpperCase()

These methods can change the case of a string:

let str = 'United States';
console.log(str.toLowerCase());
console.log(str.toUpperCase());

Output

united states
UNITED STATES

Tutorials

Strings in Typescript are quite similar to Javascript. You can learn more about commonly used functions with strings in the articles below.

Summary

Most of the time, you can use the string type to store textual data. They come with several operations and methods, allowing you to perform basic and advanced text manipulation in TypeScript. Also, don’t forget to check out other guides on our sites to get familiar with other techniques when working with TypeScript strings.

Leave a Reply

Your email address will not be published. Required fields are marked *