Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I interpolate variable values in the javascript or typescript string?

Variables File:

export class VariableSettings {

   public static string_value: string = 'vikas/${id}/data';


}

Other File.

import {VariableSettings} from './variables';


    getData(id:string ){
      console.log(`${VariableSettings.string_value}`, `${id}`); 

      // it prints vikas/${id}/data abcd11123

    }`

Now I want the result like that "vikas/abcd11123/data". So how can I inject the id in that string.

Any suggestion regarding the same will be appreciated.

Thanks

like image 575
VIKAS KOHLI Avatar asked May 07 '18 06:05

VIKAS KOHLI


People also ask

How do you interpolate a string in JavaScript?

You can add values into a JavaScript string using a template literal. This is a dollar sign followed by a pair of curly brackets. Within the curly brackets should be the expression whose value you want to embed in the string.

How do you do string interpolation in TypeScript?

Rules and Regulations for TypeScript String Interpolation String Interpolation replaces the placeholders with values of string literals of any type. As these are very useful in the modern programming language, in TypeScript, they are enclosed using backticks “ which denotes the string's start and end.

Can we use interpolation in TS file?

So anything that works in JavaScript is also valid in TypeScript. And since TypeScript does not have its own syntax for string interpolation, any explanation from JavaScript applies here as well.

What do you use for modern string interpolation in JavaScript?

In JavaScript, the template string implements the string interpolation. A template string is defined by wrapping a sequence of characters into a pair of backticks `I'm template string` . The template string placeholders have the format ${expression} , for example `The number is ${number}` .


1 Answers

To use interpolated strings you need to use the `` string separator as you do in your second snippet. If you already used a non interpolated string to hold the value of your setting, there is no way you can then interpolate it using the interpolation feature (you could use a regex to perform replacement but that is a bit messy).

The simplest solution is to make the field a function and have id as a parameter

export class VariableSettings {
    public static USER_BOOKINGS = (id: number) => `vikas/${id}/data`;
}
console.log(`${VariableSettings.USER_BOOKINGS(10)}`);
console.log(VariableSettings.USER_BOOKINGS(10)); // Or no interpolation at call site, not needed anymore if you just need the single value

The USER_BOOKINGS will now be a function that takes as arguments the parameters needed to construct the string. This way the parameters needed for the strings are clear and type-safe.

like image 126
Titian Cernicova-Dragomir Avatar answered Oct 06 '22 00:10

Titian Cernicova-Dragomir