Open In App

TypeScript String

In TypeScript, the string is sequence of char values and also considered as an object. It is a type of primitive data type that is used to store text data. The string values are used between single quotation marks or double quotation marks, and also array of characters works same as a string. TypeScript string work with the series of character.

Syntax



var var_name = new String(string); 

Property:

Methods:



Example:




let uname = new String("Hello geeksforgeeks");  
console.log("Message: " + uname);  
console.log("Length: " + uname.length);

Output:

Message: Hello geeksforgeeks
Length: 19

Template String: Template string support in TypeScript from ES6 version. Template strings are used to fixed the expressions into strings.

Example:




let emplName:string =  "Mohit Jain";   
let compName:string = "geeksforgeeks";   
// Pre-ES6  
let emplDetail1: string = emplName + " works in the " + compName + " company.";   
// Post-ES6  
let emplDetail2: string = `${emplName} works in the ${compName} company.`;   
console.log("Before ES6: " +emplDetail1);  
console.log("After ES6: " +emplDetail2);

Output:

Before ES6: Mohit Jain works in the geeksforgeeks company.
After ES6:  Mohit Jain works in the geeksforgeeks company.

Multi-Line String: ES6 provides us to write the multi-line string. This can be shown in the below example.
We have to add “\n” at the end of each string for containing a new line in the string. This represents the clear cut statement.
Example:




let multi = ' hello\n ' +  
    'Geeksforgeeks\n ' +  
    'my\n ' +  
    'name\n ' +  
    'is\n ' +  
    'Mohit Jain';  
console.log(multi);  

Output:

hello
Geeksforgeeks
my
name
is
Mohit Jain

String Literal Type: It is also a type of string and strings literal is a sequence of characters enclosed in double quotation marks (” “) and terminated with a null value. In a string literal type is a type whose expected value is a string with textual contents equal to that of the string literal type. In other words, we can say a string literal allow us to specify the exact string value specified in the string literal type. While a string literal type uses different allowed string value then use “pipe” or ” | ” symbol between them.

Syntax:

Type variableName = "value1" | "value2" | "value3"; // upto N number of values  

String literal can be used in two ways:


Article Tags :