LoginSignup
0
0

More than 1 year has passed since last update.

Nodeでメッセージ中の文字列を置き換え方法メモ

Last updated at Posted at 2021-07-06

メッセージ中の文字列を置き換え

メッセージ中に置き換え対象の文字が有る場合、どのようにメッセージをフォーマットする方法があるか考えたのでメモ。

とりあえず、標準機能でどうかと、モジュール追加でどうかという意味で、思いついた順番に書いています。
案1,2は標準機能で、案3,4はモジュール追加で実施するパターンです。

案1:テンプレートリテラル ・・・ ×:eval利用は微妙

  • やろうと思えばできるが、evalによる再評価が必要になるので個人的には却下
an1.js
// メッセージをファイルから取ってきたと想定して・・・
const message = 'Hello ${name} !'

// メッセージの置き換え用
const name = 'taro'

// メッセージをテンプレートリテラルとして再評価
console.log(eval("`" + message + "`")) // → 「Hello taro !」がコンソールに出力

案2:util.format ・・・ ○:普通に使える

an2.js
const {format} = require('util')

// メッセージをファイルから取ってきたと想定して・・・
const message = 'Hello %s %s !'

// メッセージの置き換え用
const name1 = 'taro'
const name2 = 'hanako'

// メッセージをテンプレートリテラルとして再評価
console.log(format(message, name1, name2)) // → 「Hello taro hanako !」がコンソールに出力

参考:https://nodejs.org/api/util.html#util_util_format_format_args

案3:string-template ・・・ ◎:使い勝手良い

  • 更新が行われていないので使うか悩む、けど良さそう
an3-1.js
const format = require('string-template')

// メッセージをファイルから取ってきたと想定して・・・
const message = 'Hello {name1} {name2} !'

// メッセージの置き換え用
const placeholder = {
  name1: 'taro',
  name2: 'hanako'
}

// メッセージをテンプレートリテラルとして再評価
console.log(format(message, placeholder )) // → 「Hello taro hanako !」がコンソールに出力
an3-2.js
const format = require('string-template')

// メッセージをファイルから取ってきたと想定して・・・
const message = 'Hello {0} {1} !'

// メッセージの置き換え用
const placeholder = ['taro', 'hanako']

// メッセージをテンプレートリテラルとして再評価
console.log(format(message, placeholder )) // → 「Hello taro hanako !」がコンソールに出力

参考:https://www.npmjs.com/package/string-template

案4:sprintf-js ・・・ △:使えるけどイマイチ

an4-1.js
const sprintf= require('sprintf-js').sprintf

// メッセージをファイルから取ってきたと想定して・・・
const message = 'Hello %(name1)s %(name2)s !'

// メッセージの置き換え用
const placeholder = {
  name1: 'taro',
  name2: 'hanako'
}
// メッセージをテンプレートリテラルとして再評価
console.log(sprintf(message, placeholder )) // → 「Hello taro hanako !」がコンソールに出力

参考:https://www.npmjs.com/package/sprintf-js

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0