Node.js – util.format() 方法
util.format() 方法返回一个格式化的字符串,它使用第一个参数作为类似于 printf 的格式字符串。此格式还可以包含零个或多个格式说明符。这些说明符可以用来自对应参数的转换值替换。
以下是一些格式说明符
- %s − 字符串将用于转换所有值,但 BigInt、对象 和 -0 除外。
- %d − 在这种情况下,数字将用于转换所有值,但 BigInt 和 符号 除外。
- %i − 对于所有值(BigInt 和 符号 除外),将使用 parseInt(value, 10)。
- %f − 对于所有值(符号 除外),将使用 parseFloat(value)。
- %j − 此格式类型表示 JSON。
- %o − 这将使用通用的 JavaScript 对象格式表示对象。
- %c − 此说明符将被忽略,并跳过传入的任何 CSS。
- %% − 此操作不使用参数。
语法
util.format(format, [args])
参数
参数定义如下
- format − 此输入参数将接收类似于 printf 格式字符串的说明符输入。
- args − 这是传递的参数列表。
示例 1
创建一个名为“format.js”的文件并复制以下代码片段。创建文件后,使用命令“node format.js”运行此代码。
// Node.js util.format() demo Example
// Importing the util module
const util = require('util');
function fun1() {
var val1 = util.format('%s:%s:%s', 'tutorialsPoint');
var val2 = util.format('%s:%s','a', 'b', 'c', 'd');
var val3 = util.format(10, 20, 30);
var val4 = util.format('%% : %s : %d');
var val5 = util.format('%% : %s', 786);
console.log(val1, '
', val2, '
',val3, '
', val4, '
', val5);
}
// Function call
fun1();输出
C:\home
ode>> node format.js tutorialsPoint: :a:b c d 10 20 30 %% : %s : %d % : 786
示例 2
// Node.js program to demonstrate
// the util.format() method
// Import the util module
const util = require('util');
// Passing -0 to %s
console.log("1.", util.format(
'%%: %s', 'abc', 'def', -0));
// Passing a bigInt to string specifier
console.log("2.", util.format('%s',
'abc', 123456789009876543213456789));
// Passing an object with null identifier
console.log("3.", util.format('%s',
'abc', Object.create(null,
{ [Symbol.toStringTag]:
{ value: 'def' } })));
// Passing string to Number specifier
console.log("4.", util.format('%d',
'abc', 94303685));
// Passing symbol and number to int formatter
console.log("5.", util.format(
'%i', '2020 year 2021, ', 'He was 40,'
, '10.33, ', '10, ', 10));
// Passing string and Numbers
// to parseFloat specifier
console.log("6.>", util.format('%f',
'94321321321.564000 year 6546',
'abc', 943036854775807));
// Passing a class with the below value to object formatter
console.log("7. ", util.format('%o:%d',
class Foo { get [Symbol.toStringTag]()
{ return 'abc'; } },
'abc',
12345678900987
));输出
C:\home
ode>> node format.js 1. %: abc def 0 2. abc 1.2345678900987654e+26 3. abc [Object: null prototype] [def] {} 4. NaN 94303685 5. 2020 He was 40, 10.33, 10, 10 6.> 94321321321.564 abc 943036854775807 7. { [Function: Foo] [length]: 0, [prototype]: Foo [abc] { [constructor]: [Circular], [Symbol(Symbol.toStringTag)]: [Getter] }, [name]: 'Foo' }:NaN 12345678900987
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP