Typescript 中的字符串插值,用变量替换 'placeholders'

String interpolation in Typescript, replacing 'placeholders' with variables

我似乎找不到关于这个话题的足够明确的答案,所以我问这个问题:

在 C# 中,我可以执行以下操作,例如:

var text = "blah blah";
var strTest = String.Format("This is a {0}", text); //output: 'This is a blah blah'

我如何在 Typescript 中实现这一点?

用法:

我正在从 environment.ts 文件中加载一个 URL,这个字符串 URL 需要包含占位符,并且在我的服务层中,将占位符替换为实际的需要传入的参数

在我看来,使用 template stringString.Format 好得多,因为它们不会遇到糟糕的索引(错误的占位符)问题:

var text = "blah blah";
var strTest = `This is a ${text}`;
console.log(strTest);

If I do not know the name of the variables I need to pass in??

然后包裹在函数中,例如

const gen = (text) => `This is a ${text}`;

我建议在您的 environments.ts 文件中使用匿名生成器函数,这样您就可以传递所需的变量并在该函数中包含模板字符串。像这样:

environments.ts

 export const thisIsA = (str: string) => `This is a ${str}`;

一些其他文件:

import * as env from 'environments';

var text = "blah blah";
var strTest = env.thisIsA(text); //output: 'This is a blah blah'

有一个名为 localized-strings 的 npm 包,它有一个 formatString 方法,可用于以 C# 方式进行字符串插值。

import LocalizedStrings, {LocalizedStringsMethods} from "localized-strings";

interface IStrings extends LocalizedStringsMethods{
}

const localizedStrings: IStrings  = new LocalizedStrings({en: {}});
const result = localizedStrings.formatString("This is a {0}", "Text").toString();
console.log(result);

更多示例here

在你的enviornment.ts中:

export const str = "This is a {0} and this is {1}.";

在运行时随处使用:

import * as env from 'environments';

console.log(env.str.replace('{0}', 'blah blah').replace('{1}', 'again a blah blah'));