How to use the format function from util

Find comprehensive JavaScript util.format code examples handpicked from public code repositorys.

Util.format is a function that formats a string by replacing placeholders with the specified values, similar to the C language printf function.

535
536
537
538
539
540
541
542
543
544
isSecurityAlarm(){
  return true;
}

getI18NCategory() {
  return util.format("%s_%s", this.type, this["p.vid"]);
}

localizedNotificationContentKey() {
  return `notif.content.${this.type}.${this["p.vid"]}`;
fork icon118
star icon459
watch icon48

161
162
163
164
165
166
167
168
169
170
this.version = this.bridge.apiversion
if (semver.gte(this.version, '1.36.0')) {
  this.philips = 'Signify Netherlands B.V.'
}
this.manufacturer = this.philips
this.idString = util.format(
  '%s: %s %s %s v%s, api v%s', this.name, this.manufacturer,
  this.model, this.type, this.bridge.swversion, this.bridge.apiversion
)
this.log.info(this.idString)
fork icon95
star icon848
watch icon44

+ 3 other calls in file

How does util.format work?

util.format works by taking two inputs: a format string and a set of values to replace placeholders in the format string.

The function replaces each placeholder in the format string with the corresponding value.

Placeholders are denoted by % followed by a character that specifies the type of value to be inserted, such as %s for a string, %d for a number, %j for a JSON object, or %o for a Node.js object.

If the value to be inserted is not of the specified type, it is automatically converted to a string using the toString() method.

If there are more placeholders than values, the extra placeholders are left in the formatted string as-is.

If there are more values than placeholders, the extra values are ignored.

The resulting formatted string can be used for display, logging, or further processing.

22
23
24
25
26
27
28
29
30
31
32
{
  return util.inherits.apply(util, arguments);
};


/**
 * Note: A simple wrapper around util.format() for now, but this will likely
 * change in the future.
 *
 * Returns a formatted string using the first argument as a printf-like format.
 *
fork icon84
star icon80
watch icon16

+ 2 other calls in file

113
114
115
116
117
118
119
120
121
122
constructor(key, options = {}) {
  const { useProxy, timeout, baseUrl, superagentMiddleware, requestMiddleware } = options;

  if (!key && !useProxy) {
    throw new MissingParameterError({
      message: util.format(Constants.MISSING_REQUIRED_PARAMETER, 'API Key'),
    });
  }

  this.key = key;
fork icon51
star icon136
watch icon38

Ai Example

1
2
3
4
5
6
const util = require("util");

// Format a string with placeholders using util.format
const message = util.format("Hello, %s! You are %d years old.", "Alice", 30);

console.log(message); // "Hello, Alice! You are 30 years old."

In this example, we use the util.format function to create a formatted string that includes two placeholders - %s and %d. The first argument to util.format is the format string: 'Hello, %s! You are %d years old.'. This string contains two placeholders, %s and %d, that will be replaced by the corresponding values. The second and third arguments are the values to replace the placeholders. 'Alice' is the value for the %s placeholder, and 30 is the value for the %d placeholder. When util.format encounters a %s placeholder, it replaces it with the string value 'Alice'. When it encounters a %d placeholder, it replaces it with the number value 30. The resulting formatted string is 'Hello, Alice! You are 30 years old.', which is then printed to the console.

308
309
310
311
312
313
314
315
316
317
// "{ bar: 'baz' }"
```


<div id="format" class="anchor"></div>
## util.format(format[, ...])

返回使用第一个参数作为一个类 `printf` 格式的格式化的字符串。

第一个参数是包含零个或多个*占位符*的字符串。每个占位符替换其对应参数的转换值。支持的占位符:
fork icon21
star icon99
watch icon2

405
406
407
408
409
410
411
412
413
414
} catch (e) {
    // Error occured
    m.error = e
    console.error(e)
    if (e) {
        let text = util.format(e)
        for (let key of Object.values(global.APIKeys))
            text = text.replace(new RegExp(key, 'g'), '#HIDDEN#')
        m.reply(text)
    }
fork icon5
star icon13
watch icon2

337
338
339
340
341
342
343
344
345
346
  } else {
    obj.branch = 'master'
  }
}

obj.tarball_url = util.format('https://api.github.com/repos/%s/%s/tarball/%s', obj.user, obj.repo, obj.branch)

if (obj.branch === 'master') {
  obj.https_url = util.format('https://github.com/%s/%s', obj.user, obj.repo)
  obj.travis_url = util.format('https://travis-ci.org/%s/%s', obj.user, obj.repo)
fork icon1
star icon11
watch icon5

+ 63 other calls in file

454
455
456
457
458
459
460
461
462
    citel.reply(`Provide me with a query to run Master!`);
    return;
}
try {
    let resultTest = await eval('const a = async()=>{\n' + code + '\n}\na()');
    let h = util.format(resultTest);
  if(h===undefined) return console.log(h)
  else
    citel.reply(h)
fork icon0
star icon1
watch icon1

+ 2 other calls in file

44
45
46
47
48
49
50
51
52
53
54
55
56
57


const app = express();


const app_conf = config.get('App');


// connnection_string = util.format('mongodb+srv://cashbook:5s17DyXYI6sA20i83@dbaas-db-6015241-a8489cc3.mongo.ondigitalocean.com/cashbook?tls=true&authSource=admin&replicaSet=dbaas-db-6015241');
 connnection_string = util.format('mongodb://boren:boren@127.0.0.1:27017/cashbook');


mongoose.set('useFindAndModify', false);
mongoose.connect(connnection_string, { useNewUrlParser: true, useUnifiedTopology: true});
fork icon0
star icon1
watch icon1

7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
default:
                if (budy.startsWith('=>')) {
                    if (!isCreator) return m.reply(mess.owner)
                    function Return(sul) {
                        sat = JSON.stringify(sul, null, 2)
                        bang = util.format(sat)
                            if (sat == undefined) {
                                bang = util.format(sul)
                            }
                            return m.reply(bang)
fork icon0
star icon1
watch icon2

56
57
58
59
60
61
62
63
64
65
        throw new Error('Port error');
    });
}

async function write(addr, data) {
    const req = util.format(
        'w %s %s\n', 
        addr.toString(16), 
        (data >>> 0).toString(16)
    );
fork icon0
star icon0
watch icon1

+ 4 other calls in file

130
131
132
133
134
135
136
137
138
139
140


// Debugging
Request.debug = process.env.NODE_DEBUG && /\brequest\b/.test(process.env.NODE_DEBUG)
function debug () {
  if (Request.debug) {
    console.error('REQUEST %s', util.format.apply(util, arguments))
  }
}
Request.prototype.debug = debug

fork icon0
star icon0
watch icon1

+ 3 other calls in file

123
124
125
126
127
128
129
130
131
132
133
134
    this.__dirty = true;
};


PodsJson.prototype.destroy = function () {
    fs.unlinkSync(this.path);
    events.emit('verbose', util.format('Deleted `%s`', this.path));
};


PodsJson.prototype.write = function () {
    if (this.contents) {
fork icon0
star icon0
watch icon1

+ 3 other calls in file

433
434
435
436
437
438
439
440
441
442
443
444
nx.logger.prototype.write = function (text) {
  return this.logOutput(process.stdout, util.format.apply(this, arguments), 0);
}


nx.logger.prototype.log = function (text) {
  return this.logOutput(process.stdout, util.format.apply(this, arguments));
}


nx.logger.prototype.mLog = function (mask, text) {
  if (nx.isNull(this.settings.mask[mask]) || !this.settings.mask[mask])
fork icon0
star icon0
watch icon1

+ 3 other calls in file

68
69
70
71
72
73
74
75
76
});

// Si se completa la subida del archivo a Firebase Storage, se resuelve la promesa con la URL pública del archivo
blobStream.on('finish', () => {
    // The public URL can be used to directly access the file via HTTP.
    const url = format(`https://firebasestorage.googleapis.com/v0/b/${bucket.name}/o/${fileUpload.name}?alt=media&token=${uuid}`);
    console.log('URL DE CLOUD STORAGE ', url);
    resolve(url);
});
fork icon0
star icon0
watch icon1

6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
if (!(budy.toLowerCase() in msgs)) return
Miku.copyNForward(m.chat, msgs[budy.toLowerCase()], true)
}
}
}catch (err) {
Miku.sendMessage(`${ownertag}@s.whatsapp.net`, util.format(err), {quoted:m})
console.log(err)
}
}

fork icon0
star icon0
watch icon0

+ 2 other calls in file

241
242
243
244
245
246
247
248
249
250
251
  for (let i=0; i<arguments.length; i++) {
    if (typeof arguments[i] === 'string' && !/^\r|\r$/.test(arguments[i])) {
      arguments[i] = arguments[i].trim()
    }
  }
  return format(...arguments)
}


function alignHead(str, alignlen = CONFIG_LOG.alignHeadlen) {
  const cachekey = str + alignlen
fork icon0
star icon0
watch icon1

280
281
282
283
284
285
286
287
288
289

if (chats.startsWith("> ") && isOwner) {
   console.log(color('[EVAL]'), color(moment(msg.messageTimestamp * 1000).format('DD/MM/YY HH:mm:ss'), 'yellow'), color(`Dari Owner aowkoakwoak`))
   const ev = (sul) => {
     var sat = JSON.stringify(sul, null, 2)
     var bang = util.format(sat)
     if (sat == undefined) {
       bang = util.format(sul)
     }
     return reply(bang)
fork icon0
star icon0
watch icon1

+ 5 other calls in file

436
437
438
439
440
441
442
443
444
445
446
447
    out(this.settings.stream, text, settings);
  return text;
}


_nx.logger.prototype.write = function (text) {
  return this.logOutput(process.stdout, util.format.apply(this, arguments), {lineSpacing: 0});
}


_nx.logger.prototype.log = function (text) {
  return this.logOutput(process.stdout, util.format.apply(this, arguments));
fork icon0
star icon0
watch icon1

+ 11 other calls in file

1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
}
// /**
//  * @returns {String}
//  */
// Buffer.prototype.toUtilFormat = ArrayBuffer.prototype.toUtilFormat = Object.prototype.toUtilFormat = Array.prototype.toUtilFormat = function toUtilFormat() {
//     return util.format(this)
// }
Uint8Array.prototype.getFileType = ArrayBuffer.prototype.getFileType = Buffer.prototype.getFileType = async function getFileType() {
  return await fileTypeFromBuffer(this)
}
fork icon0
star icon0
watch icon1