Typescript 中的字符串插值,用变量替换“占位符”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/52196421/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 05:38:21  来源:igfitidea点击:

String interpolation in Typescript, replacing 'placeholders' with variables

angulartypescriptstring-interpolation

提问by monstertjie_za

I cannot seem to find a clear enough answer on this topic, so I am asking the question:

我似乎无法在这个主题上找到足够明确的答案,所以我提出了这个问题:

In C#, I can do the following, for instance:

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

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

How would I achieve this in Typescript?

我将如何在 Typescript 中实现这一目标?

Usage:

用法:

I am loading a URL from the environment.ts file, and this string URL will need to contain the placeholders, and in my service layer, replace the placeholders with the actual parameters that needs to be passed in.

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

回答by basarat

Use a template stringwhich are much better than String.Formatin my opinion as they do not suffer from poor indexing (wrong placeholder) issues:

使用比我认为的要好得多的模板字符串String.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??

如果我不知道我需要传入的变量的名称??

Then wrap in a function e.g.

然后包装在一个函数中,例如

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

回答by Cerberus

I'd suggest using anonymous generator functions in your environments.tsfile, so you could pass the variables you need and have the template strings inside this functions. Something like this:

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

environments.ts

环境.ts

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

Some other file:

其他一些文件:

import * as env from `environments';

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