Node.js – util.format() 方法
该方法返回一个格式化字符串,该字符串将使用第一个参数作为类似printf的格式字符串。此格式还可以包含零个或多个格式说明符。这些说明符可以替换为来自相应参数的转换值。util.format()
以下是一些格式化的说明符:
%s -字符串将用于转换除bigInt、object 和-0之外的所有值。
%d-在这种情况下,数字将被用于所有的值转换除BigInt有 和个符号
%i-parseInt(value,10)将用于除BigInt 和symbol之外的所有值。
%f-parseFloat(value)将用于除Symbol之外的所有值
%j-这种格式类型代表JSON
%o-这将代表具有通用JavaScript对象格式的对象。
%c -此说明符将被忽略并跳过传入的任何CSS。
%% -这不消耗参数。
语法
util.format(format, [args])
参数
参数定义如下:
format-此输入参数将接受说明符的输入,就像printf格式字符串。
args- 这是传递的参数列表。
示例1
创建一个文件“format.js”并复制以下代码片段。创建文件后,使用命令“nodeformat.js”运行此代码。
//Node.jsutil.format()演示示例
//导入util模块
const util = require('util');
function fun1() {
   var val1 = util.format('%s:%s:%s', 'nhooo');
   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, '\n', val2, '\n',val3, '\n', val4, '\n', val5);
}
//函数调用
fun1();输出结果C:\home\node>> node format.js nhooo: :a:b c d 10 20 30 %% : %s : %d % : 786
示例2
//Node.js程序来演示
//util.format()方法
//导入util模块
const util = require('util');
//将-0传递给%s
console.log("1.", util.format(
'%%: %s', 'abc', 'def', -0));
//将bigInt传递给字符串说明符
console.log("2.", util.format('%s',
'abc', 123456789009876543213456789));
//传递带有空标识符的对象
console.log("3.", util.format('%s',
'abc', Object.create(null,
{ [Symbol.toStringTag]:
{ value: 'def' } })));
//将字符串传递给数字说明符
console.log("4.", util.format('%d',
'abc', 94303685));
//将符号和数字传递给int格式化程序
console.log("5.", util.format(
'%i', '2020 year 2021, ', 'He was 40,'
, '10.33, ', '10, ', 10));
//传递字符串和数字
//解析Float说明符
console.log("6.>", util.format('%f',
'94321321321.564000 year 6546',
'abc', 943036854775807));
//将具有以下值的类传递给对象格式化程序
console.log("7. ", util.format('%o:%d',
   class Foo { get [Symbol.toStringTag]()
      { return 'abc'; } },
      'abc',
      12345678900987
));输出结果C:\home\node>> 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