typescript - Typescript String.format 不存在
问题描述
我有一个字符串 const 我必须替换两个单词,如下所示:
public static readonly MY_STRING: string = 'page={0}&id={1}';
0 和 1 必须替换为其他字符串。我在不同的答案中阅读了有关 String.format 的信息,他们建议提供这样的实现:
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
;
});
};
}
但是当我这样做时String.format
它告诉我
Property 'format' does not exist on type 'String'
在这种情况下,使用字符串插值/替换的正确方法是什么?使用格式我会做这样的事情:
MY_STRING.format(page, id)
我怎样才能做到这一点?
解决方案
修改原生原型(如String
. 由于 JavaScript 中的字符串没有标准或商定的format()
方法,因此添加您自己的方法可能会导致在同一运行时中运行的任何代码出现意外行为。您的实现甚至会检查现有的String.prototype.format
第一个,这意味着如果有人首先使用不同的实现到达那里,那么您可能会出现意外行为。
仅仅拥有一个stringFormat
您使用的函数绝对没有错,如下所示:
function stringFormat(template: string, ...args: any[]) {
return template.replace(/{(\d+)}/g, function (match, number) {
return typeof args[number] != 'undefined'
? args[number]
: match
;
});
};
const myString: string = 'page={0}&id={1}';
const formattedWithFormat = stringFormat(myString, 123, 456);
console.log(formattedWithFormat); // page=123&id=456
此外,JavaScript 具有提供基本相同功能的模板文字:
const myTemplate = (page: number, id: number) => `page=${page}&id=${id}`;
const formattedWithTemplate = myTemplate(123, 456);
console.log(formattedWithTemplate); // page=123&id=456
如果您打算修改的原型String
并且之前的警告并没有阻止您,那么您可以使用全局扩充或模块扩充方法来允许 TypeScript 识别您期望值string
具有format()
方法:
/* here be dragons */
interface String {
format(...args: any[]): string;
}
String.prototype.format = function (...args) { return stringFormat(String(this), ...args) };
console.log(myString.format(123, 789)); // page=123&id=789
但希望您会使用其他解决方案之一。
好的,希望有帮助;祝你好运!
推荐阅读
- php - php 7.0 不上传文件
- c# - 如何在针对 SQL Server 执行之前使用 AutoMapper 过滤列
- php - 如何在 laravel 5.3 中使用插入存储过程获取插入的 ID?
- c - epoll:使用具有许多 fd 的结构表时如何识别哪个 fd 已准备就绪
- angular - 反应式表单电子邮件字段验证未正确进行
- android - Volley ClassNotFoundException com.android.volley.Response$Listener
- sapui5 - 转到特定模式时更改应用程序标题
- java - new BigInteger(String) 给出声纳警告
- sql - 使用输入参数调用 SQL 存储过程
- python - 如果队列达到限制,Pika python 等待 RabbitMQ Publisher