템플릿은 문자열 내부에 표현식을 포함할 수 있도록 ES6에 도입되었습니다. '' 또는 "" 따옴표 대신 백틱(``)을 사용합니다. 그들은 훨씬 더 나은 문자열 보간 방법을 제공하며 표현식은 ${a+b}와 같은 방식으로 포함될 수 있습니다. + 연산자보다 훨씬 좋은 구문을 제공합니다.
다음은 JavaScript의 템플릿 문자열에 대한 코드입니다 -
예시
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
body {
font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
}
.result {
font-size: 20px;
font-weight: 500;
color: blueviolet;
}
</style>
</head>
<body>
<h1>Template strings in JavaScript</h1>
<div class="result"></div>
<button class="Btn">CLICK HERE</button>
<h3>Click on the above button to add two numbers and display them</h3>
<script>
let resEle = document.querySelector(".result");
let a = 22;
let b = 44;
function add(a, b) {
return a + b;
}
document.querySelector(".Btn").addEventListener("click", () => {
resEle.innerHTML = `The sum of ${a} and ${b} = ${add(a, b)}`;
});
</script>
</body>
</html> 출력

'여기를 클릭' 버튼을 클릭하면 -
