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

更新於:2021年8月16日

2K+ 次瀏覽

啟動您的職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.