Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

trim
string
typescript
communitycreator

What is the string.trim() method in TypeScript?

Theodore Kelechukwu Onyejiaku

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Overview

In TypeScript, the trim() method is used to remove whitespace from both sides of a string. This method is also available in JavaScript because it is a subset of TypeScript. However, TypeScript offers much more.

Syntax

string.trim()
Syntax for trim() method in TypeScript

Parameters

This method takes the parameter string, which represents the string we want to remove whitespace from both of its sides.

Return value

This method returns a string with the whitespace removed from both ends.

Note: This method does change or modify the original string.

Example

// export our code
export {}

// create some strings in TypeScript
let string1:string = "  Welcome to Edpresso      "
let string2:string = " This is the best educative platform   "
let string3:string = " You are welcome! "

// print strings and their lengths
console.log("STRINGS:")
console.log(string1, string1.length)
console.log(string2, string2.length)
console.log(string3, string3.length)

// remove white spaces from both sides of the strings
let result1 = string1.trim()
let result2 = string2.trim()
let result3 = string3.trim()

// print trimmed strings and their lengths
console.log("\nTRIMMED STRINGS:")
console.log(result1, result1.length)
console.log(result2, result2.length)
console.log(result3, result3.length)
Trim a string in TypeScript using the trim() method

Explanation

  • Line 2: We export our code to avoid variable name scoping errors.
  • Lines 5–7: We create the strings we want to trim.
  • Lines 11–13: We print the strings and their length.
  • Lines 16–18: We trim the strings and store the results in some variables.
  • Lines 22–24: We print the trimmed strings along with their length.

RELATED TAGS

trim
string
typescript
communitycreator

CONTRIBUTOR

Theodore Kelechukwu Onyejiaku

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring