String.Format
在TypeScript
中不起作用
错误:
The property 'format' does not exist on value of type '{ prototype: String; fromCharCode(...codes: number[]): string; (value?: any): string; new(value?: any): String; }'.
attributes["Title"] = String.format(
Settings.labelKeyValuePhraseCollection["[WAIT DAYS]"],
originalAttributes.Days
);
答案 0 :(得分:91)
注意:从TypeScript 1.4开始,TypeScript中提供了字符串插值:
var a = "Hello";
var b = "World";
var text = `${a} ${b}`
这将编译为:
var a = "Hello";
var b = "World";
var text = a + " " + b;
JavaScript String
对象没有format
函数。 TypeScript不会添加到本机对象,因此它也没有String.format
函数。
对于TypeScript,您需要扩展String接口,然后需要提供implementation:
interface String {
format(...replacements: string[]): string;
}
if (!String.prototype.format) {
String.prototype.format = function() {
var args = arguments;
return this.replace(/{(\d+)}/g, function(match, number) {
return typeof args[number] != 'undefined'
? args[number]
: match
;
});
};
}
然后您可以使用该功能:
var myStr = 'This is an {0} for {0} purposes: {1}';
alert(myStr.format('example', 'end'));
你可以也考虑string interpolation(模板字符串的一个功能),这是一个ECMAScript 6功能 - 虽然将它用于String.format
用例,你会仍然需要将它包装在一个函数中,以便提供包含格式和位置参数的原始字符串。它通常与内插的变量一起使用,因此您需要使用参数进行映射以使其适用于此用例。
例如,格式字符串通常定义为稍后使用...这不起作用:
// Works
var myFormatString = 'This is an {0} for {0} purposes: {1}';
// Compiler warnings (a and b not yet defines)
var myTemplateString = `This is an ${a} for ${a} purposes: ${b}`;
因此,要使用字符串插值而不是格式字符串,您需要使用:
function myTemplate(a: string, b: string) {
var myTemplateString = `This is an ${a} for ${a} purposes: ${b}`;
}
alert(myTemplate('example', 'end'));
格式字符串的另一个常见用例是它们被用作共享的资源。我还没有发现一种在不使用eval
的情况下从数据源加载模板字符串的方法。
答案 1 :(得分:29)
如果您的唯一目标是消除丑陋的字符串连接和无聊的字符串转换,您可以使用 TypeScript的本机字符串插值:
var yourMessage = `Your text ${yourVariable} your text continued ${yourExpression} and so on.`
注意:
在赋值语句的右侧,分隔符既不是单引号也不是双引号,而是特殊字符,称为反引号或重音。
TypeScript编译器会将右侧特殊文字转换为字符串连接表达式。换句话说,此语法不依赖于ECMAScript 6功能而是依赖于本机TypeScript功能。您生成的javascript代码仍然兼容。
答案 2 :(得分:5)
您可以非常轻松地 声明 :
declare module String{
export var format:any;
}
String.format('','');
这是假设String.format在其他地方 定义 。例如在Microsoft Ajax Toolkit中:http://www.asp.net/ajaxlibrary/Reference.String-format-Function.ashx
答案 3 :(得分:3)
FIDDLE: https://jsfiddle.net/1ytxfcwx/
NPM: https://www.npmjs.com/package/typescript-string-operations
GITHUB: https://github.com/sevensc/typescript-string-operations
我为String实现了一个类。它并不完美但它对我有用。
使用它,就像这样:
var getFullName = function(salutation, lastname, firstname) {
return String.Format('{0} {1:U} {2:L}', salutation, lastname, firstname)
}
export class String {
public static Empty: string = "";
public static isNullOrWhiteSpace(value: string): boolean {
try {
if (value == null || value == 'undefined')
return false;
return value.replace(/\s/g, '').length < 1;
}
catch (e) {
return false;
}
}
public static Format(value, ...args): string {
try {
return value.replace(/{(\d+(:.*)?)}/g, function (match, i) {
var s = match.split(':');
if (s.length > 1) {
i = i[0];
match = s[1].replace('}', '');
}
var arg = String.formatPattern(match, args[i]);
return typeof arg != 'undefined' && arg != null ? arg : String.Empty;
});
}
catch (e) {
return String.Empty;
}
}
private static formatPattern(match, arg): string {
switch (match) {
case 'L':
arg = arg.toLowerCase();
break;
case 'U':
arg = arg.toUpperCase();
break;
default:
break;
}
return arg;
}
}
修改强>
我扩展了类并在github上创建了一个存储库。如果你可以帮助改进它会很棒!
https://github.com/sevensc/typescript-string-operations
或下载npm包
答案 4 :(得分:2)
我这样解决了;
1。创建一个函数
export function FormatString(str: string, ...val: string[]) {
for (let index = 0; index < val.length; index++) {
str = str.replace(`{${index}}`, val[index]);
}
return str;
}
2。按如下所示使用它;
FormatString("{0} is {1} {2}", "This", "formatting", "hack");
答案 5 :(得分:1)
我正在使用TypeScript版本3.6
,我可以这样做:
let templateStr = 'This is an {0} for {1} purpose';
const finalStr = templateStr.format('example', 'format'); // This is an example for format purpose
答案 6 :(得分:0)
作为实现相同目的的解决方法,您可以使用sprintf-js库和types。
我是从另一个SO answer获得的。
答案 7 :(得分:0)
如果你使用 NodeJS,你可以使用内置的 util 函数:
import * as util from "util";
util.format('My string: %s', 'foo');
文档可以在这里找到: https://nodejs.org/api/util.html#util_util_format_format_args