简体   繁体   English

如何在javascript或typescript字符串中插入变量值?

[英]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". 现在我希望结果像“vikas / abcd11123 / data”。 So how can I inject the id in that string. 那么如何在该字符串中注入id。

Any suggestion regarding the same will be appreciated. 任何有关相同的建议将不胜感激。

Thanks 谢谢

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 最简单的解决方案是使字段成为函数并将id作为参数

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. USER_BOOKINGS现在将是一个函数,它将构造字符串所需的参数作为参数。 This way the parameters needed for the strings are clear and type-safe. 这样,字符串所需的参数是清晰且类型安全的。

you can try: 你可以试试:

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

let re = /id/gi; 
let newstr = `${VariableSettings.USER_BOOKINGS}`.replace(re, `${id}`);
console.log(newstr); 
     export class VariableSettings {
       id:number;
       public static string_value: string;


    constructor(){
      this.id = 123456
      VariableSettings.string_value = `vikas/${this.id}/data`;
}
  ngOnInit() {
    console.log(VariableSettings.string_value);
  }
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM