What is the string.trim() method in TypeScript?
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 codeexport {}// create some strings in TypeScriptlet string1:string = " Welcome to Edpresso "let string2:string = " This is the best educative platform "let string3:string = " You are welcome! "// print strings and their lengthsconsole.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 stringslet result1 = string1.trim()let result2 = string2.trim()let result3 = string3.trim()// print trimmed strings and their lengthsconsole.log("\nTRIMMED STRINGS:")console.log(result1, result1.length)console.log(result2, result2.length)console.log(result3, result3.length)
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.