자바스크립트 템플릿 리터럴 이란 자바스크립트 표현식을 사용가능케 하는 문자열 리터럴을 이야기 합니다. 여러 줄로 이루어진 문자열 혹은 표현식이 삽입된 문자열 표현을 가능케 합니다.
백틱(Back Tick ` ) 사용을 통한 문자열 삽입
백틱 을 사용하여 직접 문자열 안에 변수를 사용할 수 있습니다.
사용법은 ` ${ 변수 } ` 의 형태입니다.
<body>
<script>
let age = 30;
let introdue = `Hi! my age is ${age}`;
console.log( introdue );
</script>
</body>
아래는 또다른 예제입니다.
<body>
<script>
const isSizeBig = false;
function checkSize() {
console.log( isSizeBig ? "$40" : "$20" );
}
console.log( checkSize() );
</script>
</body>
자바스크립트 템플릿 리터럴 에서 여러 라인의 문자열 만들기
이전 ES5에서는 다음과 같이 백슬래시 형태로 문자열을 생성했습니다.
<body>
<script>
let multiLine = "34, Dongsan-ro 16-gil ,\n"
+ "Seocho-gu, \n"
+ "Seoul, \n"
+ "Republic of Korea";
console.log( multiLine );
</script>
</body>
ES6에서는 백틱(`)으로 감싸서 연결하면 됩니다.
<body>
<script>
let multiLine2 = `34, Dongsan-ro 16-gil ,
Seocho-gu,
Seoul,
Republic of Korea`;
console.log( multiLine2 );
</script>
</body>
템플릿 리터럴 내부에서도 줄바꿈이 가능합니다.
<body>
<script>
const printLongLine = (continues) => {
const text = `a very long string that just ${continues}${""
} and ${continues} and ${continues}`;
return text;
};
console.log(printLongLine("continues"));
</script>
</body>
자바스크립트 템플릿 리터럴 에 표현식 삽입하기 – 삼항연산자
템플릿 문자열에는 표현식을 삽입할 수 있습니다. 삼항 연산자를 활용하여 true, false의 결과에 따라 분기되는 리턴값을 사용할 수 있습니다.
<body>
<script>
const student1 = {
name : "철수",
age : 20,
subject : "economy"
}
const student2 = {
name : "영희",
age : 21,
subject : "Computer"
}
const text = ( student ) =>{
console.log( `${ student.name}, ${ student.age} : ${ student.subject == "economy" ? "문과" : "이과" }` );
}
text( student1 );
text( student2 );
</script>
</body>
템플릿 리터럴에 함수 전달하기
템플릿 리터럴에 함수를 전달하여, 해당 함수의 처리 결과를 템플릿 리터럴에 적용할 수 있습니다.
<body>
<script>
const itemList = ["스탠드", "책상", "컴퓨터", "스마트폰"];
const printArray = () =>{
return itemList.map( (item) =>{
return item = item + "||";
})
}
const string = `아이템 목록 : ${printArray(itemList)} `;
console.log(string);
</script>
</body>
다음과 같이 태그드 템플릿(Tagged Template) 형태로 활용할 수 있습니다.
<script>
let subject1 = 'SAPUI5';
let subject2 = "자바스크립트";
//strings는 배열의 형태로 들어온다.
function taggedSTmp(stringArray, subject1, subject2) {
//stringArray변수에는 순수 텍스트인 부분만 배열형태로 들어롬
stringArray.forEach(element => {
console.log( element );
});
let str = stringArray[0] + subject1 + " " + subject2 + stringArray[2];
return str;
}
let result5 = taggedSTmp`이 내용는 ${subject1} 에 대한 ${subject2} 기초 강좌`;
console.log(result5);
</script>
taggedSTemp 함수에 첫번째 파라메터로 템플릿 리터럴에 포함된 요소 중 순수 텍스트 인 부분만을 추출하여 배열로 던져줍니다. 즉, ${} 부분으로 split한 개념이라고 쉽게 생각하면 됩니다.
이상으로 템플릿 리터럴의 주요 내용에 대해 알아보았습니다. 좀 더 상세한 사항을 알고자 한다면 모질라 이 문서를 참고해보시기 바랍니다.
자바스크립트의 다양한 문자열 메소드의 예제는 여기서 확인해 볼 수 있습니다.