util.format() 으로 문자열 동적 생성하기

자바스크립트에서 문자열을 동적으로 생성하기 위해서는 보통 ``와 같이 백틱을 많이 사용한다.

하지만 노드 환경에서 제공하는 util의 format 메서드를 사용하면, 마치 C언어에서 문자열을 만드는 것 처럼 동적으로 문자열을 생성할 수 있다.

 

const util = require('util');

const str1 = util.format('%d, %s, %j', 10, '안녕', { name: 'Park'});
console.log("str : ", str1, "\ntype :", typeof str1);
/*
str :  10, 안녕, {"name":"Park"} 
type : string
*/
const endpoint1 = "hi";
const endpoint2 = "bye";
const str2 = util.format("https://testtest/dummy/%s/%s", endpoint1, endpoint2);
console.log("str2 : ", str2);
// str2 :  https://testtest/dummy/hi/bye

위와 같이 다른 언어에서 지원되는 것 처럼 문자열을 동적으로 생성할 수 있게 된다.