How to use eval() function In Typescript
In this approach, we are using the eval() function to perform string interpolation within a regular string. By wrapping the string in backticks and using ${} placeholders, the eval() function is used to evaluate the expression, by replacing ${website} and ${category} with their corresponding values, printing in the final formatted string.
Syntax:
let result: string = eval("`String content with ${variable1} and ${variable2}`");
Example: The below example uses the eval() function to format strings in TypeScript.
Javascript
let website: string = "w3wiki" ; let category: string = "Programming" ; let message: string = "Visit ${website} for ${category} articles." ; console.log(eval( "`" + message + "`" )); |
Output:
"Visit w3wiki for Programming articles."
How to Format Strings in TypeScript ?
In TypeScript, the formatting of strings consists of structuring and concatenating the strings to make them in a properly readable format. We can use various approaches to format the strings in TypeScript.
There are several ways to format the string in TypeScript which are as follows:
Table of Content
- Using Concatenation (+)
- Using Template Literals
- Using eval() function