Introduction
In this chapter, we will explore the string
type in TypeScript. The string
type is used to represent textual data. Understanding how to work with strings is essential for handling and manipulating text in your TypeScript programs.
Table of Contents
- Definition
- String Syntax
- Basic Operations with Strings
- Common String Methods
- Template Literals
- Complete Example with Output
- Conclusion
Definition
In TypeScript, the string
type is used to represent sequences of characters. Strings are used to store and manipulate text. TypeScript provides various methods and operations to work with strings effectively.
String Syntax
Syntax
let variableName: string = "value";
Example
let name: string = "Ramesh"; let greeting: string = `Hello, ${name}!`; console.log(name, greeting);
Output
Ramesh Hello, Ramesh!
Basic Operations with Strings
TypeScript supports various basic operations on strings, such as concatenation, accessing characters, and comparing strings.
Example
let firstName: string = "Ramesh"; let lastName: string = "Kumar"; // Concatenation let fullName: string = firstName + " " + lastName; console.log(`Full Name: ${fullName}`); // Output: Ramesh Kumar // Accessing Characters let firstChar: string = firstName[0]; console.log(`First Character: ${firstChar}`); // Output: R // Comparing Strings let isSame: boolean = firstName === lastName; console.log(`Are Names Same: ${isSame}`); // Output: false
Output
Full Name: Ramesh Kumar First Character: R Are Names Same: false
Common String Methods
TypeScript provides various built-in methods for working with strings. These methods are available on the String
object.
Example
let message: string = "Hello, TypeScript!"; // toUpperCase let upperCaseMessage = message.toUpperCase(); console.log(`Upper Case: ${upperCaseMessage}`); // Output: HELLO, TYPESCRIPT! // toLowerCase let lowerCaseMessage = message.toLowerCase(); console.log(`Lower Case: ${lowerCaseMessage}`); // Output: hello, typescript! // substring let substringMessage = message.substring(7, 17); console.log(`Substring: ${substringMessage}`); // Output: TypeScript // split let words = message.split(" "); console.log(`Words: ${words}`); // Output: [ 'Hello,', 'TypeScript!' ] // length let lengthMessage = message.length; console.log(`Length: ${lengthMessage}`); // Output: 17 // charAt let charAtMessage = message.charAt(0); console.log(`Character at Index 0: ${charAtMessage}`); // Output: H // includes let includesMessage = message.includes("Type"); console.log(`Includes 'Type': ${includesMessage}`); // Output: true // startsWith let startsWithMessage = message.startsWith("Hello"); console.log(`Starts with 'Hello': ${startsWithMessage}`); // Output: true // endsWith let endsWithMessage = message.endsWith("!"); console.log(`Ends with '!': ${endsWithMessage}`); // Output: true // replace let replaceMessage = message.replace("TypeScript", "JavaScript"); console.log(`Replace 'TypeScript' with 'JavaScript': ${replaceMessage}`); // Output: Hello, JavaScript! // trim let paddedMessage: string = " Hello, TypeScript! "; let trimmedMessage = paddedMessage.trim(); console.log(`Trimmed: '${trimmedMessage}'`); // Output: 'Hello, TypeScript!'
Output
Upper Case: HELLO, TYPESCRIPT! Lower Case: hello, typescript! Substring: TypeScript Words: [ 'Hello,', 'TypeScript!' ] Length: 17 Character at Index 0: H Includes 'Type': true Starts with 'Hello': true Ends with '!': true Replace 'TypeScript' with 'JavaScript': Hello, JavaScript! Trimmed: 'Hello, TypeScript!'
Template Literals
Template literals provide an easy way to create multi-line strings and concatenate strings with embedded expressions. They are enclosed by backticks () and allow for interpolation using
${expression}`.
Example
let firstName: string = "Ramesh"; let lastName: string = "Kumar"; let age: number = 25; let introduction: string = `My name is ${firstName} ${lastName}. I am ${age} years old.`; console.log(introduction);
Output
My name is Ramesh Kumar. I am 25 years old.
Complete Example with Output
In this section, we will combine all the examples into a single TypeScript file, compile it to JavaScript, and run it to see the output.
TypeScript Code (src/index.ts
)
// Basic String Operations let firstName: string = "Ramesh"; let lastName: string = "Kumar"; // Concatenation let fullName: string = firstName + " " + lastName; console.log(`Full Name: ${fullName}`); // Output: Ramesh Kumar // Accessing Characters let firstChar: string = firstName[0]; console.log(`First Character: ${firstChar}`); // Output: R // Comparing Strings let isSame: boolean = firstName === lastName; console.log(`Are Names Same: ${isSame}`); // Output: false // Using String Methods let message: string = "Hello, TypeScript!"; // toUpperCase let upperCaseMessage = message.toUpperCase(); console.log(`Upper Case: ${upperCaseMessage}`); // Output: HELLO, TYPESCRIPT! // toLowerCase let lowerCaseMessage = message.toLowerCase(); console.log(`Lower Case: ${lowerCaseMessage}`); // Output: hello, typescript! // substring let substringMessage = message.substring(7, 17); console.log(`Substring: ${substringMessage}`); // Output: TypeScript // split let words = message.split(" "); console.log(`Words: ${words}`); // Output: [ 'Hello,', 'TypeScript!' ] // length let lengthMessage = message.length; console.log(`Length: ${lengthMessage}`); // Output: 17 // charAt let charAtMessage = message.charAt(0); console.log(`Character at Index 0: ${charAtMessage}`); // Output: H // includes let includesMessage = message.includes("Type"); console.log(`Includes 'Type': ${includesMessage}`); // Output: true // startsWith let startsWithMessage = message.startsWith("Hello"); console.log(`Starts with 'Hello': ${startsWithMessage}`); // Output: true // endsWith let endsWithMessage = message.endsWith("!"); console.log(`Ends with '!': ${endsWithMessage}`); // Output: true // replace let replaceMessage = message.replace("TypeScript", "JavaScript"); console.log(`Replace 'TypeScript' with 'JavaScript': ${replaceMessage}`); // Output: Hello, JavaScript! // trim let paddedMessage: string = " Hello, TypeScript! "; let trimmedMessage = paddedMessage.trim(); console.log(`Trimmed: '${trimmedMessage}'`); // Output: 'Hello, TypeScript!' // Using Template Literals let age: number = 25; let introduction: string = `My name is ${firstName} ${lastName}. I am ${age} years old.`; console.log(introduction); // Output: My name is Ramesh Kumar. I am 25 years old.
Compiling to JavaScript
To compile the TypeScript code to JavaScript, run the TypeScript compiler:
tsc src/index.ts
Output in JavaScript (src/index.js
)
// Basic String Operations var firstName = "Ramesh"; var lastName = "Kumar"; // Concatenation var fullName = firstName + " " + lastName; console.log("Full Name: " + fullName); // Output: Ramesh Kumar // Accessing Characters var firstChar = firstName[0]; console.log("First Character: " + firstChar); // Output: R // Comparing Strings var isSame = firstName === lastName; console.log("Are Names Same: " + isSame); // Output: false // Using String Methods var message = "Hello, TypeScript!"; // toUpperCase var upperCaseMessage = message.toUpperCase(); console.log("Upper Case: " + upperCaseMessage); // Output: HELLO, TYPESCRIPT! // toLowerCase var lowerCaseMessage = message.toLowerCase(); console.log("Lower Case: " + lowerCaseMessage); // Output: hello, typescript! // substring var substringMessage = message.substring(7, 17); console.log("Substring: " + substringMessage); // Output: TypeScript // split var words = message.split(" "); console.log("Words: " + words); // Output: [ 'Hello,', 'TypeScript!' ] // length var lengthMessage = message.length; console.log("Length: " + lengthMessage); // Output: 17 // charAt var charAtMessage = message.charAt(0); console.log("Character at Index 0: " + charAtMessage); // Output: H // includes var includesMessage = message.includes("Type"); console.log("Includes 'Type': " + includesMessage); // Output: true // startsWith var startsWithMessage = message.startsWith("Hello"); console.log("Starts with 'Hello': " + startsWithMessage); // Output: true // endsWith var endsWithMessage = message.endsWith("!"); console.log("Ends with '!': " + endsWithMessage); // Output: true // replace var replaceMessage = message.replace("TypeScript", "JavaScript"); console.log("Replace 'TypeScript' with 'JavaScript': " + replaceMessage); // Output: Hello, JavaScript! // trim var paddedMessage = " Hello, TypeScript! "; var trimmedMessage = paddedMessage.trim(); console.log("Trimmed: '" + trimmedMessage + "'"); // Output: 'Hello, TypeScript!' // Using Template Literals var age = 25; var introduction = "My name is " + firstName + " " + lastName + ". I am " + age + " years old."; console.log(introduction); // Output: My name is Ramesh Kumar. I am 25 years old.
Running the JavaScript
To see the output of the compiled JavaScript code, run the JavaScript file using Node.js:
node src/index.js
Conclusion
In this chapter, we covered the string
type in TypeScript, including how to declare and use string variables, perform basic string operations, use various string methods, and create template literals. We provided a complete example with its output to illustrate how strings work in TypeScript. Understanding the string
type is essential for handling and manipulating text in your TypeScript programs.