자바스크립트에서 문자열을 동적으로 생성하기 위해서는 보통 ``와 같이 백틱을 많이 사용한다.
하지만 노드 환경에서 제공하는 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
위와 같이 다른 언어에서 지원되는 것 처럼 문자열을 동적으로 생성할 수 있게 된다.
'JavaScript' 카테고리의 다른 글
javascript 스코프와 실행 컨텍스트 (0) | 2023.01.31 |
---|---|
javascript의 호이스팅(hoisting) 알아보기 (0) | 2023.01.24 |
JSON과 JSON.stringify, JSON.parse (0) | 2023.01.16 |
자바스크립트 클로저(Closures)란? (0) | 2023.01.11 |
Promises의 all, race, allSettled 사용하기 (0) | 2023.01.09 |