TypeScript – Strings


TypeScript – Strings


”;


In TypeScript, a string represents a sequence of characters. The string type is a fundamental data type in TypeScript. Strings are important to hold data that can be represented in text form. Like JavaScript, TypeScript also supports both string primitives and String objects.

The String object lets you work with a series of characters. It wraps the string primitive data type with a number of helper methods.

You can invoke methods on primitive strings because TypeScript automatically wraps the string primitive and call the methods on wrapper object. The same applies to properties also.

Creating Strings

Strings in TypeScript can be created as primitives from string literals or as objects using the String() constructor.

You can use the following syntax to create a String object in TypeScript −

cost str = new String(value);

Here str is the newly created String object and value is a series of characters.

You can create string primitives using single quote, double quotes and backtick.

let str1: string = ''a string primitive'';
let str2: string = "another string";
let str3: string = `yet another string`;

The string primitives can also be created using the String() function without new keyword.

let str: string = String(value);

”string” is a primitive, but ”String” is a wrapper object. Prefer using ”string” when possible.

String Properties

A list of the methods available in String object along with their description is given below −

S.No. Property & Description
1. Constructor

Returns a reference to the String function that created the object.

2. Length

Returns the length of the string.

3. Prototype

The prototype property allows you to add properties and methods to an object.

String Methods

A list of the methods available in String object along with their description is given below −

S.No. Method & Description
1. charAt()

Returns the character at the specified index.

2. charCodeAt()

Returns a number indicating the Unicode value of the character at the given index.

3. concat()

Combines the text of two strings and returns a new string.

4. indexOf()

Returns the index within the calling String object of the first occurrence of the specified value, or -1 if not found.

5. lastIndexOf()

Returns the index within the calling String object of the last occurrence of the specified value, or -1 if not found.

6. localeCompare()

Returns a number indicating whether a reference string comes before or after or is the same as the given string in sort order.

7.

match()

Used to match a regular expression against a string.

8. replace()

Used to find a match between a regular expression and a string, and to replace the matched substring with a new substring.

9. search()

Executes the search for a match between a regular expression and a specified string.

10. slice()

Extracts a section of a string and returns a new string.

11. split()

Splits a String object into an array of strings by separating the string into substrings.

12. substr()

Returns the characters in a string beginning at the specified location through the specified number of characters.

13. substring()

Returns the characters in a string between two indexes into the string.

14. toLocaleLowerCase()

The characters within a string are converted to lower case while respecting the current locale.

15. toLocaleUpperCase()

The characters within a string are converted to upper case while respecting the current locale.

16. toLowerCase()

Returns the calling string value converted to lower case.

17. toString()

Returns a string representing the specified object.

18. toUpperCase()

Returns the calling string value converted to uppercase.

19. valueOf()

Returns the primitive value of the specified object.

Examples

Let’s understand the string types with the help of some examples in TypeScript.

Example: Creating String Primitives

In the example below, we use single quote, double quote and backtick to create the primitive strings str1, str2 and str3 respectively.

let str1: string = ''a string primitive'';
console.log(str1);
let str2: string = "another string";
console.log(str2);
let str3: string = `yet another string`;
console.log(str3);

On compiling, it will generate the following JavaScript code.

let str1 = ''a string primitive'';
console.log(str1);
let str2 = "another string";
console.log(str2);
let str3 = `yet another string`;
console.log(str3);

The output of the above example code is as follows −

a string primitive
another string
yet another string

Example: Creating String Objects

Here we create a String object using the String() constructor with new keyword.

const email = new String(''[email protected]'');
console.log(email);
console.log(typeof email);

On compiling, it will generate the following JavaScript code.

const email = new String(''[email protected]'');
console.log(email);
console.log(typeof email);

The output of the above example code is as follows −

[email protected]
object

Example: Concatenating TypeScript strings

To concatenate two string, we can use + operator. Here, we concatenate two strings str1 and str2 and display the result in the console.

let str1: string = "Hello ";
let str2: string = "World!";
let str3: string = str1 + str2;
console.log(str3);

On compiling, it will generate the following JavaScript code.

let str1 = "Hello ";
let str2 = "World!";
let str3 = str1 + str2;
console.log(str3);

The output of the above example code is as follows –

Hello World!

Example: Accessing string elements using indexing

In the example below, we access the string characters from the 1st and 6th indices.

let message: string = "Hello World!";
console.log("Character at index 1 is => " + message[1]);
console.log("Character at index 6 is => " + message[6]);

On compiling, it will generate the following JavaScript code.

let message = "Hello World!";
console.log("Character at index 1 is => " + message[1]);
console.log("Character at index 6 is => " + message[6]);

The output of the above example code is as follows −

Character at index 1 is => e
Character at index 6 is => W

Example: String vs. string in TypeScript

In TypeScript, type ”String” is a wrapper object and type ”string” is a primitive type. These both types can’t be assigned to each other.

In the example below, we tried to assign a string object to a variable of type string primitive.

let str: string;
str = new String(''shahid'');

The above example code will show the following error −

Type ''String'' is not assignable to type ''string''.
  ''string'' is a primitive, but ''String'' is a wrapper object. Prefer using ''string'' when possible.

It is always advised to use string primitives.

Advertisements

”;

Leave a Reply

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